on_ready和on_消息事件从未触发?

2024-04-26 13:01:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我的想法是一个类来处理所有传入和传出到不一致服务器的消息。这样以后我就可以把它和不同的IRC类型的通道一起使用来同步它们。在

但是首先我想开发这个类,但是我不能让它响应消息。我打算使用web钩子,这就是我使用重写库的原因。在

这就是我的类的外观和使用方式,但是我不能让它看到不一致的消息,而只需在响应该消息时键入hello。在

class DiscordChat:

    def __init__(self):
        self.client = discord.Client()
        self.WEBHOOK_ID = aNumber
        self.WEBHOOK_TOKEN = "AWebHookToken"
        self.DISCORD_BOT_TOKEN = "ABotToken"
        self.__webhook = Webhook.partial(self.WEBHOOK_ID, self.WEBHOOK_TOKEN,adapter=RequestsWebhookAdapter())

    def get_client(self):
        return self.__client
    def set_client(self,value):
        self.__client = value

    def send(self, message,username):
        self.__webhook.send("Hello World from DiscordChat: " + message, username=username)

    async def on_ready(self):
        print('Logged in as')
        print(self.client.user.name)
        print(self.client.user.id)
        print('------')

    async def on_message(self,message):
        print(message.content)
        await message.channel.send('Hello! ' + message.author.name  )

    def run(self):
        self.client.run(self.DISCORD_BOT_TOKEN)

    client = property(get_client,set_client)


class TDCRBot:
    def __init__(self):
        print("initializin main program")

    def run(self):
        print("Running program!")
        self.main()

    def main(self):
        print("hello from Main program!")
        objDiscordChat = DiscordChat()

        objDiscordChat.run()

        objDiscordChat.send("Test Message for Discord Streaming text channel","TestUser Sil3ntDragon")

if __name__ == "__main__":
    app = TDCRBot()
    app.run()

我知道我做错了什么我只是不知道是什么。在

例如,我在很多例子中都看到了@client.event的用法,但是当我尝试使用它时,我得到一个错误,说client没有定义。我预感到这可能是个问题,但这只会给我留下一个更大的问题:我应该如何定义{}?在


Tags: runnameselfclienttokensend消息message
1条回答
网友
1楼 · 发布于 2024-04-26 13:01:00

既然client.event是一个装饰师,你知道的

@dec
def func():
    ...

相当于:

^{pr2}$

客户机被定义为实例变量,因此可以在__init__中注册事件。下面是一个精简版的工作代码(如果您愿意,可以添加其他所有内容):

import discord

class DiscordChat:

    def __init__(self):
        self.client = discord.Client()
        self.on_ready = self.client.event(self.on_ready)
        self.on_message = self.client.event(self.on_message)

    async def on_ready(self):
        print('Logged in as')
        print(self.client.user.name)
        print(self.client.user.id)
        print('   ')

    async def on_message(self, message):
        print(message.content)
        await message.channel.send('Hello! ' + message.author.name)

    def run(self):
        self.client.run("Token")


class TDCRBot:
    def __init__(self):
        print("initializin main program")

    def run(self):
        print("Running program!")
        self.main()

    def main(self):
        print("hello from Main program!")
        objDiscordChat = DiscordChat()
        objDiscordChat.run()

if __name__ == "__main__":
    app = TDCRBot()
    app.run()

相关问题 更多 >