尝试使用Discord.py重写将消息发送到特定频道,但它不起作用 [英] Trying to send a message to a specific channel using Discord.py rewrite and it isn't working
问题描述
我目前正在开发Discord机器人,并且试图在用户升级后使用Discord.py rewrite将消息发送到特定频道,并且出现此错误:
I'm currently working on a discord bot and I'm trying to send a message to a specific channel using Discord.py rewrite once the user levels up, and I'm getting this error:
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"cogs\userdata.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"cogs\userdata.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
我真的不确定这是什么问题,但是如果有人知道这个问题,请让我知道如何解决这个问题,我将不胜感激.
I'm really not sure what the issue is here but if anyone knows the problem I would be very appreciative if you could let me know how I can correct this.
感谢您的阅读,我已经尝试了好几个小时.
Thanks for reading I've been trying to figure this out for hours.
仍然存在问题.
推荐答案
您会收到 AttributeError
,因为 channel
为None.
You get AttributeError
because channel
is None.
要解决此问题,您需要像这样删除频道ID中的引号:
To fix it you need to remove quotes from channel id like this:
channel = bot.get_channel(636399538650742795)
此处对此进行了描述: https://discordpy.readthedocs.io/en/latest/migrating.html#snowflakes-are-int
This is described here: https://discordpy.readthedocs.io/en/latest/migrating.html#snowflakes-are-int
我在下一行还看到另一个错误. channel
也没有 message
属性.我认为您需要像这样修复它:
Also i see another error on the next line. The channel
has no message
attribute too. I think you need to fix it like this:
await channel.send(f"{message.author.mention} is now level {self.users[author_id]['level']}! congrats!")
这篇关于尝试使用Discord.py重写将消息发送到特定频道,但它不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!