因此,我对python还不熟悉,更不熟悉如何在不和谐的情况下编写机器人代码。目前我正在使用discord.py和red (https://docs.discord.red/en/stable/index.html)。
目前,我正试图让机器人听一条新消息,并打印响应它的东西,但我就是搞不明白。由于我使用的是red,所以我没有使用client = discord.Client()和在代码本身上设置令牌,所以使用@client.event()似乎不起作用,也不使用@bot.event(),而且我也找不到任何其他方法让机器人侦听on_message()事件。
用我的部分代码编辑:
import discord
from discord.ext import commands
from redbot.core import commands
class MyCog(commands.Cog):
client = discord.Client()
def __init__(self, bot):
self.bot = bot
@bot.event()
async def on_message(self, message):
if 'test' in message.content:
await self.send_message(message.channel, 'it works!')控制台返回未定义@bot.event()中的机器人。
另外还有一个单独的初始化文件,它是这样做的,以遵循Red关于如何制作齿轮的指导。
from .remind import MyCog
def setup(bot):
bot.add_cog(MyCog(bot))发布于 2022-07-20 21:49:49
这里是一个齿轮的例子,它回答了提到的一个特定的单词。它也有一个冷却,以防止机器人垃圾邮件,我认为绝对包括在内。
from curses.panel import bottom_panel
import discord
from discord.ext import commands
class brilliant(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._cd = commands.CooldownMapping.from_cooldown(1, 60.0, commands.BucketType.member) # Change accordingly
# rate, per, BucketType
def ratelimit_check(self, message):
"""Returns the ratelimit left"""
bucket = self._cd.get_bucket(message)
return bucket.update_rate_limit()
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user:
return
msg = message.content.lower()
brilliant = ['brilliant', 'Brilliant', 'brilliant!', 'Brilliant!']
if any(word in msg for word in brilliant):
retry_after = self.ratelimit_check(message)
if retry_after is None:
await message.channel.send("Brilliant!")
await self.bot.process_commands(message)
else:
return
async def setup(bot):
await bot.add_cog(brilliant(bot))如果您希望它在主文件中,您可以放一些简单得多的东西:
brilliant = ['brilliant', 'Brilliant', 'brilliant!', 'Brilliant!']
@bot.event
async def on_message(message):
if message.author == bot.user:
return
msg = message.content.lower()
if any(word in msg for word in brilliant):
await message.channel.send("Brilliant!")
await bot.process_commands(message)希望能帮上忙。
https://stackoverflow.com/questions/73057835
复制相似问题