【问题标题】:Python Discord bot not reading filesPython Discord bot不读取文件
【发布时间】:2020-07-07 20:13:39
【问题描述】:

我一直在为我的 discord 机器人开发一个 ..joke 函数,它读取一个包含笑话列表的文件并随机选择一个。当.joke 运行时,什么都没有发生,没有错误,什么都没有。经过一番调试,我发现问题出在打开文件的位置。但是当我在不同的文件(单独)中运行读取功能时,它可以工作。我做错了什么?

import random
import discord
from discord.ext import commands

class joke(commands.Cog):
     def __init__(self, client):
         self.client = client

     @commands.Cog.listener()
     async def on_ready(self):
          print("loaded!")

     @commands.command()
     async def joke(self, ctx):
          file = open("jokes.txt", "r", encoding="utf8") #it appears it stops working here
          jokes = file.readlines()
          ctx.send(random.choice(jokes))

def setup(client):
     client.add_cog(joke(client))

【问题讨论】:

    标签: python python-3.x discord.py-rewrite


    【解决方案1】:

    我认为您需要在ctx.send 之前添加await。这个函数的例子(我不使用self,因为它不是一个类):

    @client.command()
    async def joke(ctx):
        with open("joke.txt", "r", encoding='utf-8') as file:
            await ctx.send(random.choice(file.readlines()))
    

    最好使用with open 而不是open,因为您忘记添加file.close()

    您的代码:

    @commands.command()
    async def joke(self, ctx):
        file = open("jokes.txt", "r", encoding="utf8") #it appears it stops working here
        jokes = file.readlines()
        await ctx.send(random.choice(jokes))
    

    【讨论】:

    • 我目前在 cog 中使用它,这就是我在函数中使用 @commands.command() 和 self 的原因。我刚刚尝试了您的建议,但没有运气。我在终端中没有错误。我也在主 python 文件中尝试过,但也没有用。打开文件时,它看起来仍然是个问题。
    • 您是否在ctx.send 之前添加await?因为是async函数,需要加上await。
    • 我在你的代码中添加了await,它对我很有效。
    • 我改了答案。
    • 刚刚尝试了新代码,仍然无法正常工作:/。我检查了它的文件权限,它们都是正确的,还尝试以 sudo 运行,但它仍然无法正常工作。我也有await ctx.send - 这与我使用 Raspberry Pi 运行它有什么不同吗?我对此表示怀疑。
    猜你喜欢
    • 2018-10-18
    • 2018-10-30
    • 2019-08-12
    • 2022-11-17
    • 2022-01-04
    • 2018-07-08
    • 2021-04-11
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多