尝试使用重写向特定通道发送消息 Discord.py 但不起作用



我目前正在研究一个不和谐的机器人,我正在尝试使用 Discord.py 用户升级后重写向特定频道发送消息,并且收到此错误:

await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
AttributeError: 'NoneType' object has no attribute 'message'

这是所有代码:

import discord
from discord.ext import commands
import json
import asyncio
class Levels(commands.Cog):
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
author_id = str(message.author.id)
bot = commands.Bot(command_prefix='!')
if author_id not in self.users:
self.users[author_id] = {}
self.users[author_id]['level'] = 1
self.users[author_id]['exp'] = 0
self.users[author_id]['exp'] += 1
if author_id in self.users:
if self.lvl_up(author_id):
channel = bot.get_channel('636399538650742795')
await channel.message.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
def __init__(self, bot):
self.bot = bot
with open(r"cogsuserdata.json", 'r') as f:
self.users = json.load(f)
self.bot.loop.create_task(self.save_users())
async def save_users(self):
await self.bot.wait_until_ready()
while not self.bot.is_closed():
with open(r"cogsuserdata.json", 'w') as f:
json.dump(self.users, f, indent=4)
await asyncio.sleep(5)

def lvl_up(self, author_id):
author_id = str(author_id)
current_xp = self.users[author_id]['exp']
current_lvl = self.users[author_id]['level']
if current_xp >= ((3 * (current_lvl ** 2)) / .5):
self.users[author_id]['level'] += 1
return True
else:
return False

我真的不确定这里的问题是什么,但如果有人知道这个问题,如果您能让我知道如何纠正这个问题,我将不胜感激。

感谢您的阅读,几个小时以来我一直在试图解决这个问题。

编辑:仍然有问题。

你会得到AttributeError,因为channel是None。

要修复它,您需要从通道 ID 中删除引号,如下所示:

channel = bot.get_channel(636399538650742795)

下面描述如下:https://discordpy.readthedocs.io/en/latest/migrating.html#snowflakes-are-int


我也在下一行看到另一个错误。channel也没有message属性。我认为您需要像这样修复它:

await channel.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")

我能够使用本指南发送消息:https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel 我使用的代码是:

channel = client.get_channel(12324234183172)
await channel.send('hello')
@bot.command()
async def lvl_up(member: discord.Member):
"""Send a level up message"""
channel = bot.get_channel(channel_id) # channel id should be an int
if not channel:
return

await channel.send(f"GG {member}, u lvled up") # Whatever msg u want to put

尝试将该代码用于通道并发送消息,然后添加逻辑。我是堆栈溢出的新手,所以如果我正确格式化该代码,idk

不确定这是否解决了(对不起,我是堆栈溢出的新手(,但使用它就可以工作

@bot.command()
async def Hello(ctx):
channel = bot.get_channel(Insert Channel ID)
await channel.send('Hello')

使用这个我没有收到NoneType错误。

你需要把它放在一个异步函数中

所以而不是

channel = bot.get_channel(<channel id>)

你应该做

async def get_channel():
channel = bot.get_channel(<channel id>)
asyncio.run(get_channel())