python - 自我机器人无法使用 cogs 运行功能?
问题描述
我正在运行我从 YouTube 教程中找到的这个脚本,并且它之前工作过。现在它似乎不再工作了。
不工作的脚本
import asyncio
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='', help_command=None, self_bot=False)
class SelfBot(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def sendMessage(self, ctx):
await ctx.send("Send Message")
client.add_cog(SelfBot(client))
client.run(token, bot=False)
似乎它被“卡住”@commands.command()
并且不会运行 sendMessage 函数。一旦脚本运行,我的机器人似乎也在线。关于如何解决它的任何想法?
我发现有趣的另一件事是,我创建的一个脚本确实按预期工作。
正在运行的脚本
@bot.event
async def on_message(message):
await asyncio.sleep(1)
with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send("test")
return
bot.run(token, bot=False)
一旦我向服务器发送消息,这将向我发送消息测试。
解决方案
您的命令可能不起作用,因为您有一个on_message
事件。on_message
事件优先于命令,如果你不处理它们,它们都将无法执行。
您必须在您的on_message
活动中添加:
@bot.event
async def on_message(message):
await asyncio.sleep(1)
with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send("test")
await bot.process_commands(message)
如果它不能解决问题,它也可能来自您的commands.Bot
变量。由于未知原因,您似乎有两个commands.Bot
变量:client
和bot
. 你应该只有一个。
另外,我看到您将前缀设置为''
,如果您不希望出现类似 的任何错误Command not found
,则应设置前缀(例如,,,,!
... $
);
。
此外,正如@InsertCheesyLine 推荐的那样,您应该将您的 cog 分隔在不同的文件中,并将它们放在一个 nammed 文件夹中cogs
,如下所示:
主文件(例如bot.py
)
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
extensions = ['cogs.test'] #cogs.(filename)
if __name__ == '__main__':
for extension in extensions:
bot.load_extension(extension)
@bot.event
async def on_ready():
print(f'Bot is ready to go!')
bot.run('TOKEN')
你的一个齿轮(例如cogs/test.py
)
from discord.ext import commands
#This is a cog example, you'll have to adapt it with your code
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener() #equivalent to @bot.event
async def on_message(self, message):
if 'test' in message.content:
await message.channel.send('Test Message')
await self.bot.process_commands(message)
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(bot):
bot.add_cog(Test(bot))
推荐阅读
- python - 在函数中返回 None:TypeError:“NoneType”类型的对象没有 len()
- authentication - laravel 中只有一个函数的两个中间件
- sqlite - 如何通过更新当前活动中的数据库来刷新以前活动中的 ListView?
- laravel - Laravel:雄辩模型中的多个多态关系
- c# - WPF mvvm 路由
- javascript - SweetAlert2 不工作并在 IE11 中停止
- python - np.loadtxt 忽略标题,如何保存标题数据?
- php - 使用 jQuery Ajax 和 PHP 从 URL 上传图片
- android - 我们可以通过 Thingworx PTC 开发移动应用程序吗?
- java - Spring MVC - 获取 HttpServletResponse 主体