在循环中使用 client.run() 和 client.close() 在第二次运行时给出"session is closed"



警告:在此处完成discord.py noob(以及Python(。我正在尝试制作一个Discord机器人,当有产品可用时会警告我,所以我有一个主要的.py文件,该文件使用selenium firefox运行一个循环,检查可用性,并且该部分运行良好。在这个循环中,当产品可用时,我试图使用一个连接Discord Bot并警告我的功能。然后,我可以通过Discord与机器人互动,并告诉它继续寻找更多,这会断开机器人的连接,程序就会从主循环中出来,直到它返回到调用discordbot的函数(因此它重新连接bot,等待交互,然后重复(。因此,它第一次运行得很好,但在循环的第二次运行时,Bot不会重新连接,并且告诉会话已关闭(程序仍在运行(。以下是Discord Bot功能的代码:

import discord
import time
#Discord Bot parameters
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
channelFirefox = [here goes the discord channel ID]
#Tarjetas
t1 = ["1111","1/11","111"]
t2 = ["2222","2/22","222"]
t3 = ["3333","3/33","333"]
t4 = ["444","4/44","444"]

def botFunction(channelFirefox):
#Discord Bot routines
@client.event
async def on_ready():
channel = client.get_channel(channelFirefox)
print(f'We have logged in as {client.user}')
await channel.send('Productos pillados !')
await channel.send('Para comprar: comprar t1/t2/t3/t4')
await channel.send('Para continuar: y ')
await channel.send('Para parar: parar ')

@client.event
async def on_message(message):
global procesoCompra,tarjeta

if message.channel.id == channelFirefox:
if message.author == client.user:
return
if message.content.startswith('comprar t1'):
await message.channel.send('Comprando con tarjeta 1')
procesoCompra = "comprar"
tarjeta = t1
await client.close()


if message.content.startswith('comprar t2'):
await message.channel.send('Comprando con tarjeta 2')
procesoCompra = "comprar"
tarjeta = t2
await client.close()

if message.content.startswith('comprar t3'):
await message.channel.send('Comprando con tarjeta 3')
procesoCompra = "comprar"
tarjeta = t3
await client.close() 

if message.content.startswith('comprar t4'):
await message.channel.send('Comprando con tarjeta 4')
procesoCompra = "comprar"
tarjeta = t4
await client.close()


if message.content.startswith('y'):
await message.channel.send('Continua buscando')
procesoCompra = "y"
tarjeta = ["000","0/0","0"]   
await client.close()


if message.content.startswith('parar'):
await message.channel.send('Este perfil ha sido parado')
procesoCompra = "stop"
tarjeta = ["000","0/0","0"]
await client.close()


client.run([HERE GOES THE BOT TOKEN])

return procesoCompra,tarjeta

基本上,我希望能够多次运行这个函数,但似乎client.run((和client.close((不能是"回环";。任何帮助都将不胜感激!

起初,我在主代码中有这个函数,但我收到了同样的错误,所以我试着把它放在文件之外,但我仍然收到了相同的错误(尽管有错误,程序仍在运行(。主程序运行良好,我以前使用过它,但通过命令控制台进行交互,我只是决定通过Discord Bot添加控制。

我能问一下你的机器人的目的是什么吗?我很困惑你为什么会这样:await client.close在经历了我认为是命令之后,关闭你的机器人与discord的连接的目的是什么?如果你能告诉我这件事,我想我会帮你的。另外,我可以建议使用@client.command装饰器,而不是通过on_message事件创建和调用命令吗?在我看来,这要容易得多,效果也要好得多。以下是Discord.py API参考中的链接:https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#commands

最新更新