是否可以在函数外发送消息?

时间:2021-03-19 10:15:59

标签: python python-3.x discord discord.py

我正在编写一个 discord.py 脚本,我想为我的原始代码发出警报,但我不知道如何正确编写它:

@client.event
async def on_ready():
    print('Client is ready.')

    channel = client.get_channel(00000000000000)
    await channel.send(f'example')

这很好用,但是当我在外面写它时它不想工作。有没有办法写这个部分?

channel = client.get_channel(000000000000000)
await channel.send(f'message')

2 个答案:

答案 0 :(得分:3)

一切都必须是异步的,所以它必须在一个函数中

>>> import subprocess
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

然后您可以在 on_ready 或其他异步函数中执行 async def sendmsg(): channel = client.get_channel(000000000000000) await channel.send(f'message')

答案 1 :(得分:0)

函数外的代码在您启动文件时被调用。因此,由于机器人尚未准备好,您不能说它来获取频道并向其发送消息。

因此您必须将 public string GenerateDigest() { string json = @"{'hello':'world'}"; string hashedData = ComputeSha256Hash(json); return string.Format("{0}{1}", "SHA-256=", hashedData); } static string ComputeSha256Hash(string rawData) { using (SHA256 sha256Hash = SHA256.Create()) { byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData)); return System.Convert.ToBase64String(bytes); } } 放在另一个函数中,当特定事情发生时调用。

同样如 FluxedScript 所说,你必须把它放到一个异步函数中,因为它里面有一个 channel = ... await channel.send,然后你必须用 await 调用它。