[英]discord.py retrieving data from json file not responding
抱歉,問題標題不清楚。 我不知道有什么其他的說法。
我做了一個命令,上面寫着p!channel [channel_id]
,它基本上創建了一個我的機器人將用“e”響應的頻道。 我希望命令將channel_id
和guild_id
存儲到名為channel.json
的 json 文件中,當用戶發送消息時,它將檢查消息是否在channel_id
頻道中,如果在頻道中,將發送“ e”。 但是,它沒有響應,也沒有顯示錯誤代碼。 有人可以幫忙嗎? 代碼如下:
def get_channel(client,message):
with open("channel.json", "r") as f:
e = json.load(f)
return e[str(message.guild.id)]
@client.command()
@commands.has_permissions()
async def channel(ctx, *, channelid):
with open("channel.json", "r") as f:
e = json.load(f)
e[str(ctx.guild.id)] = channelid
with open("channel.json", "w") as f:
json.dump(e,f)
await ctx.send(f"Successfully setup <#{channelid}>")
@client.event
async def on_message(message):
if message.channel.id == get_channel:
await message.channel.send('e')
有幾個直接的問題使其無法正常運行。
get_channel
,而不是調用它。 通道的 ID 不等於 function 本身,因此消息永遠不會發送。 你想要get_channel(client, message)
。on_message
事件確保您的命令永遠不會被調用。ctx.send()
而不是ctx.channel.send()
。False
。此外,您還可以改進以下幾點:
get_channel
function 從未使用過client
,因此您可以將 function 定義更改為簡單地get_channel(message)
。has_permissions
檢查不會檢查任何內容,因此在您的代碼中它什么也不做。這是一個改進的版本,它在啟動時讀取保存的文件(如果存在)。 然后它將 ID 作為一個集合保存在 memory 中,並且僅在需要添加新 ID 時打開文件。
from discord.ext import commands
import json
client = commands.Bot(command_prefix='p!')
try:
with open('channels.json') as f:
client.ids = set(json.load(f))
print("Loaded channels file")
except FileNotFoundError:
client.ids = set()
print("No channels file found")
@client.command()
async def channel(ctx, channel_id):
try:
channel_id = int(channel_id)
except ValueError:
await ctx.channel.send("Channel must be all digits")
return
if channel_id in client.ids:
await ctx.channel.send(f"Channel <#{channel_id}> is already set up.")
return
client.ids.add(channel_id)
with open('channels.json', 'w') as f:
json.dump(list(client.ids), f)
await ctx.channel.send(f"Successfully set up <#{channel_id}>")
@client.event
async def on_message(message):
if message.channel.id in client.ids and message.author != client.user:
await message.channel.send('e')
# Pass processing on to the bot's command(s)
await client.process_commands(message)
client.run(TOKEN)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.