python - 从 Discord Bot 发送消息时遇到问题
问题描述
我目前正在尝试使用 Python 制作一个 Discord 机器人,以自动化一些无聊的东西。我目前只是想制作一些可以响应消息的东西,然后发回一些东西。
我的代码在这里:
import discord
TOKEN = '(The correct Token, hidden for obvious reasons)'
client = discord.Client()
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('!hello'):
msg = 'Hello {0.author.mention}'.format(message)
await client.send(message.channel, msg)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
当我运行这段代码时,机器人会出现在网上,并在有人键入 !hello 时识别出来。但是,紧接着,它在尝试发送消息“AttributeError:'Client' object has no attribute 'send'”时返回错误
在这一点上,我已经在这里待了几个小时,任何人都将不胜感激
解决方案
考虑到这有“!” 在它的开头,我们可以通过更改以下内容将其转换为命令并使其更紧凑,而不是使其成为 on_message 事件!
原始代码:
import discord
TOKEN = '(The correct Token, hidden for obvious reasons)'
client = discord.Client()
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.startswith('!hello'):
msg = 'Hello {0.author.mention}'.format(message)
await client.send(message.channel, msg)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
编辑代码:
import discord
from discord.ext import commands #imports the commands module
client = commands.Bot(command_prefix = '!')
@client.command()
async def Hello(ctx):
await ctx.send(f'Hello {ctx.message.author}')
#the rest is the same as your original code
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run('Token')
希望这会有所帮助!祝你好运,-兰登
推荐阅读
- python - 从 skrules 导入 SkopeRules ImportError:无法导入名称“六”
- javascript - 适合画布的标签并使用不同的颜色chartjs
- amazon-web-services - 在 AWS 上托管 Elasticsearch:{"error":"您需要先登录或注册才能继续。"}
- vuex - 不要在突变处理程序之外改变 vuex 存储状态 - Vuetify 小吃吧
- c - 它是一个二叉搜索树。删除元素时出现问题。为什么?
- redis - 如果我重新启动一个 REDIS 实例,删除其他的 PID 和 sock 文件
- regex - 正则表达式捕获和重新定位相同的模式
- android - 使用相同布局显示全视图和半视图时视图的BottomSheetDialog对齐
- javascript - Access Unnamed Value in Ajax Object
- blazor - 悬停并更改图像