Discord.py在试图循环日志并发送到服务器时被卡住



我正在尝试创建一个简单的discord bot,它解析不断写入的日志文件,并将新行发送到我在服务器名称日志中的discord通道。

分析文件和打印输出很容易,而且效果很好。我的问题是试图将其纳入不和之中。我的程序似乎在连接后挂起了,并且从未发送任何消息。机器人程序在服务器上创建它,并完成on_aready。

我对discord.py是个新手,所以我很感激任何指导。非常感谢。

import time, discord, asyncio, nest_asyncio
nest_asyncio.apply()
TOKEN = '123'
class MyClient(discord.Client):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
self.bg_task = self.loop.create_task(self.background_task())
async def background_task(self):
channel = discord.utils.get(ctx.guild.channels, name="logs")
with open('log.txt', 'r') as f:
while True:
line = ''
while len(line) == 0 or line[-1] != 'n':
tail = f.readline()
if tail == '':
time.sleep(0.1)
continue
line += tail
print(f"Sending: {line}")
await channel.send(line)
await asyncio.sleep(1)
client = MyClient()
client.run(TOKEN)

我也在用discord.py开发一个discordbot,所以我想我可以帮助你。我会这样做:

当机器人准备好时,它会打印出他已登录

import discord
client = discord.Client()
@client.event
async def on_ready():
print('Logged in as ' + str(client.user))

当你想查看.txt文件中的内容时,你只需要输入"显示内容">

@client.event
async def on_message(message):
if message.content == 'show content':
line = ' '
while len(line) != 0:

首先它读取最上面一行

f = open('C:\Users\USERNAME\FOLDER\logs.txt', 'r')
line = f.readline()
content_of_textfile = f.read()
f.close()

然后将其从文件中删除我知道这不是最干净的方法,我相信有更好的解决方案

f = open('C:\Users\USERNAME\FOLDER\logs.txt', 'w')
content_of_textfile.replace('line', '')
f.write(content_of_textfile)
f.close()

然后它会将消息发送到你的不和通道

await message.channel.send(line)
client.run('YOUR TOKEN')

希望这有帮助:D

最新更新