user385466
user385466

Reputation: 1

How to solve this synchro problem discord.py?

I have 2 same scripts in Python, that are being used as 2 discord bots. They have different tokens and channel's ids.

The problem is that one bot is sending same message to another on different server. For Instance, if I'm typing to one of my bots "!test" It should respond with e.g. "Hello", but it's responding as different bot on other server. I have no idea what's going on.

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)

Upvotes: 0

Views: 66

Answers (1)

itzFlubby
itzFlubby

Reputation: 2289

If I understood your problem correctly, both your bots react to the !test command, eventhoug only one should.
And this is also logical, because if both bots are on the server on wich you issue the command, and both have the same prefix, they will also both respond to your !test command. Of course they will each send the reponse to their specified channel.


If you want to use one bot for each server, specify the guild-id on which each bot should solely operate

guild_id = 123456789

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

Do this in both your script, just like you do with the channel_id


Alternatively, you could also just give them different prefixes.

Upvotes: 0

Related Questions