我正在编写一个Discord Bot,以从实时聊天中获取消息并将其中继到Discord频道,但希望它具有其他响应功能。当前,脚本通过输入while loop
来中继消息,该消息将运行直到收到正确的消息为止。
def chat_parser():
resp = sock.recv(4096).decode('utf-8')
#print(' - ', end='')
filtered_response = filter_fighter_announce(resp)
if resp.startswith('PING'):
# sock.send("PONG :tmi.twitch.tv\n".encode('utf-8'))
print("Ponging iirc server")
sock.send("PONG\n".encode('utf-8'))
return ''
elif (len(filtered_response) > 0):
if (filtered_response.count('ets are OPEN for') > 0):
filtered_response = get_fighters(filtered_response)
return filtered_response
return ''
fight = fight_tracker('') #initialize first fight object
def message_loop():
global first_loop_global
while True:
chat_reception = chat_parser()
if (chat_reception == ''):
continue
fight.set_variables(chat_reception)
return fight.announcement
return ''
与此相关的问题是,Discord的响应功能被卡住,等待该循环完成。这是其他代码供参考。
@client.event
async def on_ready():
print('Finding channel...')
for guild in client.guilds:
if guild.name == GUILD:
break
channel = guild.get_channel(salty_bet_chat_id)
print('Connected to Channel.')
try:
print('Beginning main loop.')
while True:
message_out = await message_loop()
if (message_out != None and message_out != None):
print('Sending to Discord: ', message_out)
msg = await channel.send(message_out)
await msg.add_reaction(fight.fighter_1[1])
await msg.add_reaction(fight.fighter_2[1])
print('message sent...')
except KeyboardInterrupt:
print('KeyboardInterrupt')
sock.close()
exit()
@client.event
async def on_raw_reaction_add(reaction):
print(reaction)
@client.event
async def on_message(message):
print(message.author)
print(client.user)
client.run(TOKEN)
我尝试使用chat_parser()
和message_loo()
制作异步函数,并在调用它们的地方等待它们的返回,但是代码仍在循环中阻塞。我既不熟悉异步又使用Discord的库进行编码,所以当启动Discord客户端的唯一方法是通过client.run(TOKEN)
时,我不确定如何制作异步循环功能,我无法弄清楚如何合并进入另一个事件循环。