首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >让我的不和谐机器人监听特定的消息,并在它识别出一个消息时回复。

让我的不和谐机器人监听特定的消息,并在它识别出一个消息时回复。
EN

Stack Overflow用户
提问于 2022-07-20 20:33:33
回答 1查看 211关注 0票数 -1

因此,我对python还不熟悉,更不熟悉如何在不和谐的情况下编写机器人代码。目前我正在使用discord.py和red (https://docs.discord.red/en/stable/index.html)。

目前,我正试图让机器人听一条新消息,并打印响应它的东西,但我就是搞不明白。由于我使用的是red,所以我没有使用client = discord.Client()和在代码本身上设置令牌,所以使用@client.event()似乎不起作用,也不使用@bot.event(),而且我也找不到任何其他方法让机器人侦听on_message()事件。

用我的部分代码编辑:

代码语言:javascript
复制
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关于如何制作齿轮的指导。

代码语言:javascript
复制
from .remind import MyCog


def setup(bot):
    bot.add_cog(MyCog(bot))
EN

回答 1

Stack Overflow用户

发布于 2022-07-20 21:49:49

这里是一个齿轮的例子,它回答了提到的一个特定的单词。它也有一个冷却,以防止机器人垃圾邮件,我认为绝对包括在内。

代码语言:javascript
复制
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))

如果您希望它在主文件中,您可以放一些简单得多的东西:

代码语言:javascript
复制
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)

希望能帮上忙。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73057835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档