Python Discord bot不读取文件

2024-05-19 09:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在为我的discord机器人开发一个.joke函数,它读取一个包含笑话列表的文件,然后随机选择一个。当运行.joke时,不会发生任何事情、错误,也不会发生任何事情。经过一段时间的调试,我发现问题出在它打开文件的地方。但是,当我在另一个文件中运行read函数时(单独运行),它可以工作。我做错了什么

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))

Tags: 文件函数importselfclientasyncdefrandom
1条回答
网友
1楼 · 发布于 2024-05-19 09:15:43

我认为您需要在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))

相关问题 更多 >

    热门问题