【问题标题】:Discord.py - How to run additional code after running client.run(token)?Discord.py - 如何在运行 client.run(token) 后运行附加代码?
【发布时间】:2022-12-08 09:02:47
【问题描述】:

看似简单的问题,但我坚持如何解决它。

我使用 discord.py 登录我的帐户,我想通过输入他的 user_id 来向用户发送 DM。

import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')

client = MyClient()
client.run('token')

async def send_message(user_id):
    user = client.get_user(user_id)
    await user.send('My message')

当我在我的 python shell 中运行这个 python 文件时,它会打印“Logged in as ...”成功消息并且它会挂断。它不会让我输入任何其他命令。

我只是想用一个独特的方式运行send_message函数用户身份,这样我就可以私信某个特定用户。

我该怎么做呢?

【问题讨论】:

    标签: discord.py


    【解决方案1】:

    据我所见,client.run('token') 是阻塞代码,所以它之后的任何东西都不会运行,除非它失败(如果有注销方法,也许它会在那之后继续)。

    如果要在函数中使用 client 变量,请在实例化客户端和登录之间定义它。

    import discord
    
    class MyClient(discord.Client):
        async def on_ready(self):
            print(f'Logged in as {self.user} (ID: {self.user.id})')
    
    client = MyClient()
    
    async def send_message(user_id):
        user = client.get_user(user_id)
        await user.send('My message')
    
    client.run('token')
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 2018-11-30
      • 2021-05-24
      • 2012-08-31
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多