Я хочу получать данные из другого файла Python каждый раз, когда я выполняю другойPython

Программы на Python
Anonymous
Я хочу получать данные из другого файла Python каждый раз, когда я выполняю другой

Сообщение Anonymous »

Я знаю, что всякий раз, когда я использую from my_file_contains_data.py import data_i_want
, я могу получить доступ к нужным данным и могу использовать их для операторов 'if'.
но в 'my_file_contains_data. py», «data_i_want» — это переменная, которая может изменяться.
и когда «data_i_want» изменяется, она не меняется в основном файле, с которым я работаю, и вначале всегда остается тем же значением.
Вот мои коды:
основной файл:

Код: Выделить всё

 from cmds.channelproctection import curstat
@bot.event
async def on_guild_channel_delete(channel):
if channel.guild.id == my_guild_id and curstat==1:
memberRole = channel.guild.get_role(693197190377766931) # Server's Default Member Role ID.
async for entry in channel.guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_delete):
if not entry.user.id == 472911936951156740:
try:
await entry.user.edit(nick='some swear words', roles=[memberRole], reason='Deleting a Channel.')
await channel.clone(reason=f'Channel re-opened because {entry.user.name} deleted the channel.')
chan2=bot.get_channel(my_announcement_channel)
await chan2.send(f"@everyone, {entry.user.mention}, deleted **{channel.name}** channel. some swears")
except Forbidden:
ownerid = bot.get_user(owners[0])
chan = await ownerid.create_dm()
chan3 = await bot.get_user(my_friends_id).create_dm()
await channel.clone(reason=f"@everyone, {entry.user.mention}, deleted **{channel.name}** channel. some swears")
await chan.send(f"{entry.user.name}, removed {channel.name}.")
await chan3.send(f"{entry.user.name}, removed {channel.name} ")
elif channel.guild.id == my_guild_id and curstat==0:
async for entry in channel.guild.audit_logs(limit=1, action=discord.AuditLogAction.channel_delete):
if not entry.user.id == 472911936951156740: # VoiceMaster ID
ownerid = bot.get_user(owners[0])
chan = await ownerid.create_dm()
await chan.send(f"Channel protection is off but {entry.user.name}, removed {channel.name}!")
elif channel.guild.id == IEEM and curstat not in [0, 1]:
print('there is a huge problem!')
await bot.close()

channel-protection (также известный как «my_file_contains_data»):

Код: Выделить всё

curstat=1

@commands.command(aliases = ["chanprot", 'chapro',"sex"],hidden=True)
@commands.has_guild_permissions(administrator=True)
async def channelprotection(ctx, state : str):
global curstat
if state in ["open", "turnon", "on", '1']:
if not curstat==1:
curstat = 1
await ctx.message.add_reaction("✅")
await ctx.send("Channel protection is on!",reference=ctx.message, mention_author=False)
else:
await ctx.message.add_reaction("🖕🏻")
await ctx.send("Already On.")
elif state in ['close', 'turnoff', 'off', '0']:
if not curstat==0:
curstat = 0
await ctx.message.add_reaction("✅")
await ctx.send("Caution, Channel protection is disabled!",reference=ctx.message, mention_author=False)
else:
await ctx.message.add_reaction("🖕🏻")
await ctx.send("Already Off.")
else:
await ctx.send("Use open for turning on, use close for turning of.")

async def setup(bot):
bot.add_command(channelprotection)
Когда я использовал команду выключения, она дает мне ответ, но переменная «curstat» не меняется, поэтому бот все равно воссоздает каналы, когда я или кто-то пытается удалить канал. я попробовал добавить строку из cmds.channelproctection import curstat после обработчиков событий и определить функцию
вот так:

Код: Выделить всё

@bot.event
async def on_guild_channel_delete(channel):
from cmds.channelprotection import curstat
if channel.guild.id == 693193721612861511 and curstat==1:
...
это сработало, но я не думаю, что такое использование правильное. это правда, решил ли я свою проблему или есть хороший и логичный способ «исправить» эту проблему?

Подробнее здесь: https://stackoverflow.com/questions/788 ... e-other-on

Вернуться в «Python»