簡體   English   中英

discord.py 從 json 文件中檢索數據沒有響應

[英]discord.py retrieving data from json file not responding

抱歉,問題標題不清楚。 我不知道有什么其他的說法。

我做了一個命令,上面寫着p!channel [channel_id] ,它基本上創建了一個我的機器人將用“e”響應的頻道。 我希望命令將channel_idguild_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()
  • 通道 ID 是整數,但命令 arguments 始終作為字符串讀入。 在不將參數轉換為 integer 的情況下,將其與通道 ID 進行比較將始終返回False

此外,您還可以改進以下幾點:

  • get_channel function 從未使用過client ,因此您可以將 function 定義更改為簡單地get_channel(message)
  • 此外,頻道 ID 是全球唯一的,因此您無需保存公會 ID 即可明確識別頻道。
  • 每次需要檢查 ID 時不要讀取整個文件會更有效。
  • 如果您沒有提供 arguments, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM