【发布时间】:2017-09-12 16:03:04
【问题描述】:
我创建了一个脚本,它接收格式为!notice [MM/DD/YY HH:mm], message, target 的消息,然后使用threading.Timer 调用一个函数,以便在消息中给出的UTC 时间调用它。
我遇到的问题是从此函数发送消息,无论消息的输入如何,我似乎都无法从该函数发送消息。
见下文:
import discord
import asyncio
from datetime import *
import threading
client = discord.Client()
@client.event
async def on_message(message):
if message.content[:7].lower() == "!notice".lower():
try:
notice = [datetime.strptime(message.content[message.content.find("[")+1:message.content.find("]")], "%m/%d/%y %H:%M"), message.content.split(", ")[1], message.content.split(", ")[2]]
await client.send_message(message.channel, 'Created notice "'+notice[1]+'" to be sent to '+notice[2]+' at '+str(notice[0])+' UTC.')
threading.Timer((notice[0] - datetime.utcnow()).total_seconds(), lambda a=notice[1], b=notice[2]: func(a, b)).start()
print(str((notice[0] - datetime.utcnow()).total_seconds())+" seconds until message is sent")
except (ValueError, IndexError):
await client.send_message(message.channel, 'Incorrect Notice Format.\nMust be "!notice [MM/DD/YY HH:mm], Notice contents, Target".\nEG: "!notice [01/01/2017 12:00], This is a notice, Siren Raid Team".')
def func(message, target):
print("Func called")
for i in client.servers:
for c in i.channels:
client.send_message(c, target+message)
client.run(MY_SESSION_KEY)
这会返回"Func called",所以我知道该函数正在被调用,但没有引发异常,也没有在我的聊天中发布消息。
我还尝试将func 替换为:
async def func(message, target):
print("Func called")
for i in client.servers:
for c in i.channels:
await client.send_message(c, target+message)
但是这会引发异常:
RuntimeWarning:从未等待协程“func”
坦率地说,我在这里超出了我的深度。这有什么不可行的原因吗?
我在网上看到asyncio 不是线程安全的。但是,除非我有误解,否则我的第一个示例没有在函数中使用该库。是否仍然会导致问题?
【问题讨论】:
-
现在,您的
func()将尝试向每个服务器中的每个通道发送消息,直到遇到无法发送到的通道并崩溃。您可能应该考虑使用discord.utils.get来找到您要发送的实际目标。 -
@squaswin 这是出于故障排除的目的,以检查我是否能够在任何频道上收到消息,在此之前我将
message对象传递给函数并尝试将通知发送到 @ 987654332@。此外,如果我设置logging以获取有关问题的更多信息,我不会收到任何错误,如果我尝试发送到语音频道或我无权访问的频道,我通常会这样做。
标签: python-3.x python-multithreading python-asyncio discord.py