【问题标题】:How to make my Discord Bot to work simultaneously in different servers? (discord.py)如何让我的 Discord Bot 在不同的服务器上同时工作? (discord.py)
【发布时间】:2021-07-20 10:13:16
【问题描述】:

我一直在尝试使用 discord.py 制作一个不和谐的游戏机器人。每当我运行机器人并在一个服务器上启动游戏时,我都无法在另一台服务器上启动另一个游戏。比赛变得混乱。另外我希望机器人能够在同一台服务器上处理两个不同的用户。 我将在下面发布机器人的代码。这只是一个粗略的代码,并没有得到很好的优化。所以请在代码上放轻松

import discord
import random
import asyncio

from time import sleep

client = discord.Client()

@client.event
async def on_ready():

    print(f'{client.user} has connected to Discord!')
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name="&help"))

@client.event
async def on_message(message):

    if message.author.bot:
        return

    if message.content.lower() == "&help":
        await message.channel.send(" Just a hand cricket bot :) \n&start - To start a match \nFollow along to complete the match \n(There will be glitches) ")
    
    if message.content.lower() == "&start":
        
        while True:
            
            try:
                
                await message.channel.send("Choose a number(1-10) and odd or even (For eg: 2 odd, 5 even) : ")
                msg1 = await client.wait_for('message', timeout=30)
                
                if msg1.author == message.author:
                    ch = random.randint(1,10)
                    inp = msg1.content.split()
                    
                    start = True
                    
                    if int(inp[0]) <= 10 and int(inp[0]) > 0:
                        if inp[1].lower() == "even":
                            
                            if (ch + int(inp[0])) % 2 == 0:
                                await message.channel.send(f" I chose {ch} \nYou win")
                                start = False
                                break
                            
                            else:
                                await message.channel.send(f" I chose {ch} \nYou lose")
                                break
                        
                        else:
                            
                            if (ch + int(inp[0])) % 2 != 0:
                                await message.channel.send(f" I chose {ch} \nYou win")
                                start = False
                                break
                            
                            else:
                                await message.channel.send(f" I chose {ch} \nYou lose")
                                break
                    
                    else:
                        pass
                
                else:
                    pass
            
            except asyncio.TimeoutError:
                await message.channel.send("You took too much time.")
                break
            
            except:
                await message.channel.send("Choose properly.")
        
        ch = random.choice(['Bat','Bowl'])
        await message.channel.send("Rules: Only 1-6 allowed. I will send msg after you send. If you want to quit send 0.")
        
        if start == True and ch.lower() == "bowl":
            await message.channel.send(f"I will {ch}. Send your msg for first ball")
            xyz = True
            score_h = 0
            score_b = 0
            
            while xyz:
                msg2 = await client.wait_for('message')
                
                if msg2.author == message.author and int(msg2.content) == 0:
                    await message.channel.send("Bye")
                    xyz = False
                    break
                
                elif msg2.author == message.author and int(msg2.content) < 7 and int(msg2.content) > 0:
                    choice = random.randint(1,6)
                    
                    if int(msg2.content) == choice:
                        await message.channel.send("Out!!!!!")
                        sleep(0.5)
                        await message.channel.send("I will bat now. Send your msg for first ball")
                        
                        while True:
                            msg3 = await client.wait_for('message')
                            
                            if msg3.author == message.author and int(msg3.content) == 0:
                                await message.channel.send("Bye")
                                xyz = False
                                break
                            
                            if msg3.author == message.author and int(msg3.content) < 7 and int(msg3.content) > 0:
                                choice1 = random.randint(1,6)
                                score_b += choice1
                                
                                if score_b > score_h:
                                    await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                    await message.channel.send(f"Win!! :) \nFinal Score: \nHuman: {score_h} \nBot: {score_b} \nThanks for playing :)")
                                    xyz = False
                                    break
                                
                                elif (score_b - choice1) < score_h:
                                    
                                    if int(msg3.content) == choice1:
                                        await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                        await message.channel.send(f"Out :( \nFinal Score: \nHuman: {score_h} \nBot: {score_b - choice1} \nThanks for playing :)")
                                        xyz = False
                                        break
                                    
                                    else:
                                        await message.channel.send(f"You chose {msg3.content}. I chose {choice1}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                                        sleep(0.5)
                            
                            elif msg3.author != message.author:
                                continue
                            
                            else:
                                if not msg3.author.bot: await message.channel.send("Enter correct number")
                    
                    else:
                        score_h += int(msg2.content)
                        await message.channel.send(f"You chose {msg2.content}. I chose {choice}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                        sleep(0.5)
                
                elif msg2.author != message.author:
                    continue
                
                else:
                    if not msg2.author.bot: await message.channel.send("Enter correct number")   
        
        if start == True and ch.lower() == "bat":
            await message.channel.send(f"I will {ch}. Send your msg for first ball")
            score_h = 0
            score_b = 0
            xyz = True
            
            while xyz:
                msg2 = await client.wait_for('message')
                
                if msg2.author == message.author and int(msg2.content) == 0:
                    await message.channel.send("Bye")
                    xyz = False
                    break
                
                elif msg2.author == message.author and int(msg2.content) < 7 and int(msg2.content) > 0:
                    choice = random.randint(1,6)
                    
                    if int(msg2.content) == choice:
                        await message.channel.send("Out!!!!!")
                        sleep(0.5)
                        await message.channel.send("I will bowl now. Send your msg for first ball")
                        
                        while True:
                            msg3 = await client.wait_for('message')
                            
                            if msg3.author == message.author and int(msg3.content) == 0:
                                await message.channel.send("Bye")
                                xyz = False
                                break
                            
                            if msg3.author == message.author and int(msg3.content) < 7 and int(msg3.content) > 0:
                                choice1 = random.randint(1,6)
                                score_h += int(msg3.content)
                                
                                if score_b < score_h:
                                    await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                    await message.channel.send(f"Win!! :) \nFinal Score: \nBot: {score_b} \nHuman: {score_h}\nThanks for playing :)")
                                    xyz = False
                                    break
                                
                                elif score_b > (score_h - int(msg3.content)):
                                    
                                    if int(msg3.content) == choice1:
                                        await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                        await message.channel.send(f"Out :( \nFinal Score: \nBot: {score_b} \nHuman: {score_h - int(msg3.content)} \nThanks for playing :)")
                                        xyz = False
                                        break
                                    
                                    else:
                                        await message.channel.send(f"You chose {msg3.content}. I chose {choice1}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                                        sleep(0.5)
                            
                            elif msg3.author != message.author:
                                continue
                            
                            else:
                                if not msg3.author.bot: await message.channel.send("Enter correct number")
                    
                    else:
                        score_b += choice
                        await message.channel.send(f"You chose {msg2.content}. I chose {choice}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                        sleep(0.5)
                
                elif msg2.author != message.author:
                    continue
                
                else:
                    if not msg2.author.bot: await message.channel.send("Enter correct number")
        
        elif start == False:
            await message.channel.send("1. Bat \n2. Bowl")
            cho = (await client.wait_for('message')).content
            
            if cho == "0":
                await message.channel.send("Bye")
            
            elif cho == "1":
                await message.channel.send(f"I will bowl. Send your msg for first ball")
                score_h = 0
                score_b = 0
                xyz = True
                
                while xyz:
                    msg2 = await client.wait_for('message')
                    
                    if msg2.author == message.author and int(msg2.content) == 0:
                        await message.channel.send("Bye")
                        xyz = False
                        break
                    
                    elif msg2.author == message.author and int(msg2.content) < 7 and int(msg2.content) > 0:
                        choice = random.randint(1,6)
                        
                        if int(msg2.content) == choice:
                            await message.channel.send("Out!!!!!")
                            sleep(0.5)
                            await message.channel.send("I will bat now. Send your msg for first ball")
                            
                            while True:
                                msg3 = await client.wait_for('message')
                                
                                if msg3.author == message.author and int(msg3.content) == 0:
                                    await message.channel.send("Bye")
                                    xyz = False
                                    break
                                
                                elif msg3.author == message.author and int(msg3.content) < 7 and int(msg3.content) > 0:
                                    choice1 = random.randint(1,6)
                                    score_b += choice1
                                    
                                    if score_b > score_h:
                                        await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                        await message.channel.send(f"Win!! :) \nFinal Score: \nHuman: {score_h} \nBot:{score_b} \nThanks for playing :)")
                                        xyz = False
                                        break
                                    
                                    elif (score_b - choice1) < score_h:
                                        
                                        if int(msg3.content) == choice1:
                                            await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                            await message.channel.send(f"Out :(  \nFinal Score: \nHuman: {score_h} \nBot:{(score_b - choice1)} \nThanks for playing :)")
                                            xyz = False
                                            break
                                        
                                        else:
                                            await message.channel.send(f"You chose {msg3.content}. I chose {choice1}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                                            sleep(0.5)
                                
                                elif msg3.author != message.author:
                                    continue
                                
                                else:
                                    if not msg3.author.bot: await message.channel.send("Enter correct number")
                        
                        else:
                            score_h += int(msg2.content)
                            await message.channel.send(f"You chose {msg2.content}. I chose {choice}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                            sleep(0.5)
                    
                    elif msg2.author != message.author:
                        continue
                    
                    else:
                        if not msg2.author.bot: await message.channel.send("Enter correct number")
            
            elif cho == "2":
                await message.channel.send(f"I will bat. Send your msg for first ball")
                score_h = 0
                score_b = 0
                xyz = True
                
                while xyz:
                    msg2 = await client.wait_for('message')
                    
                    if msg2.author == message.author and int(msg2.content) == 0:
                        await message.channel.send("Bye")
                        xyz = False
                        break
                    
                    elif msg2.author == message.author and int(msg2.content) < 7 and int(msg2.content) > 0:
                        choice = random.randint(1,6)
                        
                        if int(msg2.content) == choice:
                            await message.channel.send("Out!!!!!")
                            sleep(0.5)
                            await message.channel.send("I will bowl now. Send your msg for first ball")
                            
                            while True:
                                msg3 = await client.wait_for('message')
                                
                                if msg2.author == message.author and int(msg2.content) == 0:
                                    await message.channel.send("Bye")
                                    xyz = False
                                    break
                                
                                if msg3.author == message.author and int(msg3.content) < 7 and int(msg3.content) > 0:
                                    choice1 = random.randint(1,6)
                                    score_h += int(msg3.content)
                                    
                                    if score_b < score_h:
                                        await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                        await message.channel.send(f"Win!! :) \nFinal Score: \nBot: {score_b} \nHuman: {score_h} \nThanks for playing :)")
                                        xyz = False
                                        break
                                    
                                    elif score_b > (score_h - int(msg3.content)):
                                        
                                        if int(msg3.content) == choice1:
                                            await message.channel.send(f"You chose {msg3.content}. I chose {choice1}.")
                                            await message.channel.send(f"Out :( \nFinal Score: \nBot: {score_b} \nHuman: {(score_h - int(msg3.content))} \nThanks for playing :)")
                                            xyz = False
                                            break
                                        
                                        else:
                                            await message.channel.send(f"You chose {msg3.content}. I chose {choice1}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                                            sleep(0.5)
                                
                                elif msg3.author != message.author:
                                    continue
                                
                                else:
                                    if not msg3.author.bot: await message.channel.send("Enter correct number")
                        
                        else:
                            score_b += choice
                            await message.channel.send(f"You chose {msg2.content}. I chose {choice}. \nScore: \nHuman: {score_h} \nBot : {score_b}")
                            sleep(0.5)
                    
                    elif msg2.author != message.author:
                        continue
                    
                    else:
                        if not msg2.author.bot: await message.channel.send("Enter correct number")

client.run(r'token')

 

【问题讨论】:

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


    【解决方案1】:

    我在这里看到的唯一问题是,您正在使用来自timesleep(),这是阻塞的。所以不要使用sleep(0.5),而是使用await asyncio.sleep(0.5)。这应该使您的机器人可以在多个服务器中工作。

    编辑:感谢对问题的澄清,我发现了一些不同的东西。使用client.wait_for 中的check,您可以过滤哪些消息属于wait_for。因此,将其添加到 on_message 的顶部:

    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel
    

    并在每个client.wait_for 添加check=check 作为这样的参数,例如:

    msg1 = await client.wait_for('message', timeout=30, check=check)
    

    现在机器人将简单地忽略其他用户或其他服务器中的消息,并且在我测试时一切正常。

    参考资料:

    client.wait_for()

    【讨论】:

    • 感谢您的回复 但是机器人仍然将来自不同服务器上不同人的输入视为相同 我应该做哪些更改以区别对待它们?
    • 我刚刚编辑了答案以使用client.wait_for,现在它可以工作了! @UditKrishna
    猜你喜欢
    • 2018-12-08
    • 1970-01-01
    • 2019-02-04
    • 2020-09-24
    • 2021-04-20
    • 2021-05-17
    • 2021-06-13
    • 2020-08-09
    • 1970-01-01
    相关资源
    最近更新 更多