R
R
Rektar012020-09-14 19:46:33
Python
Rektar01, 2020-09-14 19:46:33

How to make 2 files work together?

Hello, here is the problem, there are 3 files. There is a main file in which the commands for the bot are stored, there is a separate file for the role system, which would add a role to the server member when adding a reaction, the code works separately, but if you start everything from the main file, only the file by roles still works. I tried to combine 2 files into one, the result is the same. How can I solve this problem? It is desirable that the main stake and code with roles be in separate files.
kendra_main:

import discord
from discord.ext import commands
from discord import utils

import cfg
import economy
import roles

@cfg.bot.command(pass_context=True) #буквально для создания команды, в скобках параметры
async def РаботаЛитон(ctx):  # создаем асинхронную фунцию бота зароботка обычного работяги
    economy.Liton.LitonBalance = economy.SalaryForWorker + economy.Liton.LitonBalance #считаем баланс
    arg = str(economy.Liton.LitonBalance) #превращает число в текст
    await ctx.send('Ты заработал денег, баланс твоего Литона : ' + arg + ' тугриков.')  # отправляем в чат ответ

@cfg.bot.command(pass_context=True)
async def РаботаКендра(ctx):  # создаем асинхронную фунцию бота зароботка обычного работяги
    economy.Kendra.KendraBalance = economy.SalaryForWorker + economy.Kendra.KendraBalance #считаем баланс
    arg = str(economy.Kendra.KendraBalance) #превращает число в текст
    await ctx.send('Ты заработал денег, баланс твоей Кендры : ' + arg + ' тугриков.')  # отправляем в чат ответ

roles.client.run(cfg.TOKEN)

cfg.bot.run(cfg.TOKEN) #запуск бота

cfg:
import discord
from discord.ext import commands
from discord import utils

bot = commands.Bot(command_prefix='!') #вот это префикс бота
TOKEN = '***'

POST_ID = 754075723219861594 #вот это  код поста
MAX_ROLES_PER_USER = 3 #вот это макс количество ролей
ROLES = {
    '':754037719956455475, #Кендра
    '':754038164175454278, #Литон
}
EXCROLES = () #исключения

roles:
import discord
from discord import utils

import cfg

#Эта гипербола отвечает за выдачу ролей
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_raw_reaction_add(self, payload):
        if payload.message_id == cfg.POST_ID:
            channel = self.get_channel(payload.channel_id)  # получаем объект канала
            message = await channel.fetch_message(payload.message_id)  # получаем объект сообщения
            member = utils.get(message.guild.members,
                               id=payload.user_id)  # получаем объект пользователя который поставил реакцию
            try:
                emoji = str(payload.emoji)  # эмоджик который выбрал юзер
                role = utils.get(message.guild.roles, id=cfg.ROLES[emoji])  # объект выбранной роли (если есть)

                if (len([i for i in member.roles if i.id not in cfg.EXCROLES]) <= cfg.MAX_ROLES_PER_USER):
                    await member.add_roles(role)
                    print('[SUCCESS] User {0.display_name} has been granted with role {1.name}'.format(member, role))

                else:
                    await message.remove_reaction(payload.emoji, member)
                    print('[ERROR] Too many roles for user {0.display_name}'.format(member))


            except KeyError as e:
                print('[ERROR] KeyError, no role found for ' + emoji)
            except Exception as e:
                print(repr(e))

client = MyClient()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
killeryStark, 2020-09-15
@killeryStark

look in the discord.py documentation about cogs. commands can be created by modules, connected and disconnected without reloading the script, etc.

_
_, 2020-09-14
@mrxor

You don't get control cfg.bot.run(cfg.TOKEN), use asyncio.gather to run both tasks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question