【问题标题】:How to solve this synchro problem discord.py?如何解决这个同步问题 discord.py?
【发布时间】:2021-05-25 04:22:21
【问题描述】:

我在 Python 中有 2 个相同的脚本,它们被用作 2 个不和谐机器人。它们有不同的令牌和频道 ID。

问题是一个机器人正在向不同服务器上的另一个机器人发送相同的消息。 例如,如果我正在输入我的一个机器人“!test” 它应该以例如响应“你好”,但它在其他服务器上响应为不同的机器人。 我不知道发生了什么。

import discord
from discord.ext.commands import Bot
import csv
 
#Logging stuff
#def setup_log():
#    import logging
        
#    logging.basicConfig(level=logging.INFO)
#    logger = logging.getLogger('discord')
#    logger.setLevel(logging.DEBUG)
#    handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
#    handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
#    logger.addHandler(handler)
#setup_log()

#Role that can give the points to others
PRIV_ROLE = 'OperatorStarć'

#PREFIX
PREFIX = '!'

#CHANNEL
CH = 846290523659567114

#TOKEN
TOKEN = 'ODAxNDc4OTMwMTIwMTc5NzMy.YAhRaw.BoUfquqW9c4l29C63VwJSf6rdVo'

#Main Prefix and instance of 'my_bot'
intents = discord.Intents.default()
intents.members = True
my_bot = Bot(command_prefix=PREFIX, intents=intents)

@my_bot.event
async def on_ready():
    from os import system, name
    if name == "nt":
        system("cls")
    else:
        system("clear")
    print("[Discord Bot has been started]")

@my_bot.event
async def on_message(message):
    #Channel on which the bot operate
    channel = my_bot.get_channel(CH)
    
    #Prefixes
    
    #TEST
    if message.content.startswith('{0}test'.format(PREFIX)):
        await channel.send('Heil Reiner!')
    
    #LISTA
    if message.content.startswith('{0}list'.format(PREFIX)):

        embed = discord.Embed(
            title="Lista Żołnierzy:",
            description="Imiona żołnierzy i ich liczba starć.",
            colour = discord.Colour.blue()
        )

        embed.set_image(url='https://cdn.discordapp.com/attachments/299534607232139265/846365370080034816/unknown.png')

        with open('data.csv', newline='', encoding='utf-8') as csvfile:
            spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
            content = ""
            for row in spamreader:
                if len(row)>0:
                    embed.add_field(name=row[0], value=row[1], inline=False)

        await channel.send(embed=embed)
    
    #DODAWANIE PUNKTÓW
    if message.content.startswith('{0}add_points'.format(PREFIX)):
        role = discord.utils.find(lambda r: r.name == PRIV_ROLE, message.guild.roles)
        if role in message.author.roles:
            content = str(message.content)[11:]
            tmp = content[content.index("+")+1:]
            tmp = tmp.replace(" ", "")
            
            if int(tmp) < 1000:
                content = content[:content.index("+")]+"+"+tmp

                #Check For Syntax
                if content.find("+") == -1:
                    await channel.send("Poprawna składnia powinna składać się z nazwy użytkownika, '+' i liczby dodawanych starć!")
                else:
                    members = []
                    r = csv.reader(open('data.csv', "r", encoding="utf-8"), delimiter=';') # Here your csv file

                    for row in r:
                        if len(row) > 0:
                            members.append(row)

                    found = 0
                    w = csv.writer(open('data.csv', "w", encoding="utf-8"), delimiter=';') # Here your csv file
                    for member in members:
                        if member[0] == content[:content.index("+")]:
                            try:
                                int(content[content.index("+")+1:])
                            except:
                                await channel.send("Niepoprawna składnia!")
                            member[1] = str(int(member[1])+int(content[content.index("+")+1:]))
                            await channel.send("Dodano {0} Starć!".format(tmp))
                            found = 1
                            w.writerows(members)

                    if found == 0:
                        w = csv.writer(open('data.csv', "a", encoding="utf-8"), delimiter=';') # Here your csv file
                        w.writerows(members)
                        w.writerow([content[:content.index("+")], content[content.index("+")+1:]])
                    
                    found = 0
        else:
            await channel.send("Nie masz odpowiednich uprawnień!")
        
    if message.content.startswith('{0}mypoints'.format(PREFIX)):
        author = message.author.nick
        if author == None:
            author = message.author.name
        author = author.strip()
        
        embed = discord.Embed(
            title=author,
            description="Twoje imię i liczba starć.",
            colour = discord.Colour.green()
        )

        embed.set_image(url=message.author.avatar_url)

        with open('data.csv', newline='', encoding='utf-8') as csvfile:
            spamreader = csv.reader(csvfile, delimiter=';', quotechar='|')
            content = ""
            for row in spamreader:
                if len(row)>0:
                    tmp = row[0]
                    tmp = tmp.strip()
                    if tmp == author:
                        embed.add_field(name="Starcia", value=row[1],inline=True)
        await channel.send(embed=embed)
    
    if message.content.startswith('{0}rem_points'.format(PREFIX)):
        role = discord.utils.find(lambda r: r.name == PRIV_ROLE, message.guild.roles)
        if role in message.author.roles:
            content = str(message.content)[11:]
            tmp = content[content.index("-")+1:]
            tmp = tmp.replace(" ", "")
            content = content[:content.index("-")]+"-"+tmp

            #Check For Syntax
            if content.find("-") == -1:
                await channel.send("Poprawna składnia powinna składać się z nazwy użytkownika, '-' i liczby odejmowanych starć!")
            else:
                members = []
                r = csv.reader(open('data.csv', "r", encoding="utf-8"), delimiter=';') # Here your csv file

                for row in r:
                    if len(row) > 0:
                        members.append(row)

                found = 0
                w = csv.writer(open('data.csv', "w", encoding="utf-8"), delimiter=';') # Here your csv file
                for member in members:
                    if member[0] == content[:content.index("-")]:
                        try:
                            int(content[content.index("-")+1:])
                        except:
                            await channel.send("Niepoprawna składnia!")
                        if int(member[1]) < int(content[content.index("-")+1:]):
                            await channel.send("Niepoprawna liczba Starć!")
                            break
                        member[1] = str(int(member[1])-int(content[content.index("-")+1:]))
                        await channel.send("Usunięto {0} Starć!".format(tmp))
                        found = 1
                        w.writerows(members)
            
                if found == 0:
                    w.writerows(members)
                
                found = 0
        else:
            await channel.send("Nie masz uprawnień!")
    if message.content.startswith('{0}help'.format(PREFIX)):
        embed = discord.Embed(
            title="POMOC",
            description="Komendy i ich działanie",
            colour = discord.Colour.orange()
        )
        embed.add_field(name="!list", value="Wyświetla starcia wszystkich użytkowników.", inline=False)
        embed.add_field(name="!add_ponts", value="Dodaje określoną liczbę  starć (składnia: !add_points nazwa.użytkowinika+liczba).", inline=False)
        embed.add_field(name="!rem_ponts", value="Usuwa określoną liczbę  starć (składnia: !rem_points nazwa.użytkowinika-liczba).", inline=False)
        embed.add_field(name="!mypoints", value="Wyświetla starcia użytkownika wpisującego komendę.", inline=False)
        embed.add_field(name="!test", value="Heil Reiner.", inline=False)
        embed.add_field(name="!help", value="Jak myślisz?", inline=False)

        await channel.send(embed=embed)

#clean the log
#def clean_log():
#    with open("discord.log", "w") as f:
#        f.write("")
#clean_log()

#RUNNING
my_bot.run(TOKEN)

【问题讨论】:

  • 如果有任何改变,我还可以补充说我正在通过 Heroku 托管机器人。
  • 不要发布您的私人令牌!您应该立即生成一个新的!
  • 也看看How to create a Minimal, Reproducible Example。删除与您的问题无关的任何额外代码,让第一次看到它的人更容易理解。
  • 机器人是否共享相同的前缀?
  • 至于令牌,虽然它不是官方令牌,但我很糟糕。前缀是相同的,但它是完全不同的机器人

标签: python discord.py


【解决方案1】:

如果我正确理解了您的问题,那么您的两个机器人都会对 !test 命令做出反应,即使只有一个机器人应该。
这也是合乎逻辑的,因为如果 both 机器人都在您发出命令的服务器上,并且 both 具有相同的前缀,它们也将 both 回复您的!test 命令。当然,他们每个人都会将响应发送到他们指定的频道。


如果您想为每台服务器使用一个机器人,请指定每个机器人应该单独操作的公会 ID

guild_id = 123456789

@my_bot.event
async def on_message(message):
    if message.guild.id != guild_id:
        return

在你的两个脚本中都这样做,就像你对 channel_id 做的那样


或者,您也可以只给它们不同的前缀。

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多