用Python替换文件中的行无法正常工作

时间:2019-07-07 22:32:26

标签: python discord.py

我正在创建一个不和谐的bot,并尝试保存有关每个用户及其发送的消息的统计信息,但是它不起作用。这就是我所拥有的:

async def update_stats():
    await client.wait_until_ready()
    global messages, author
    data = []
    if author != 0:
        try:
            with open("stats.txt", "r") as f:
                data = f.readlines()
                for item in data:
                    author2, messages2 = item.split(":")
                    print(author2, messages2)
                    index = data.index(item)

                if author == author2:

                    with open("stats.txt", "w") as f1:
                        data.pop(index)
                        novi_stat = f"""{author}:{int(messages) + int(messages2)}\n"""
                        data.insert(index, novi_stat)
                        str = ''.join(data)
                        f1.write(str)
                else:
                    with open("stats.txt", "w") as f2:
                        data.append(f"""{author}:{messages}\n""")
                        str = ''.join(data)
                        f2.write(str)

            await asyncio.sleep(5)
        except Exception as e:
            print(e)
            await asyncio.sleep(5)

这是它加载的文本文件的内容,应该在消息数量更改时更改:

DrDEagle#4984:100
kreten:123

这是我在运行代码时得到的:

DrDEagle#4984:100
kreten:123
:0

如果我发送一条消息,应该将数字从100更改为101,但是它写了一行甚至不包含正确数据的新行,我在做什么错了?

编辑:经过一个小时的编辑和重写代码,我做到了,而且有效。

import discord
import random
import aiohttp
import asyncio
import json
import datetime


client = discord.Client()
sentdex_guild = client.get_guild(No, No!) # I didn't post the code...

author = ''
messages = 0
@client.event
async def on_message(message):
    global author, messages
    author = message.author.name
    messages += 1
    authorsInFile = []

    f = open("stats.txt", 'r')
    data = f.readlines()
    for item in data:
        author2, messages2 = item.split(":")
        authorsInFile.append(author2)
        print(author2, messages2)
        if author in authorsInFile:
            index = authorsInFile.index(author)
        else:
            pass

    if author2 == author:

        f1 = open("stats.txt", "w")
        print(author)
        data.pop(index)
        novi_stat = f"""{author}:{int(messages2) + 1}\n"""
        data.insert(index, novi_stat)
        str = ''.join(data)
        f1.write(str)
        f1.close()
        f.close()

    else:
        f2 = open("stats.txt", "w")
        data.append(f"""{author}:{messages}\n""")
        str = ''.join(data)
        f2.write(str)
        f2.close()
        f.close()

    await asyncio.sleep(5)

    with open('log.txt', 'a') as f:
        f.write(f"""{datetime.datetime.now()} | {message.author} je rekao: {message.content}\n""")

    if message.content == "!bok":
        await message.channel.send("Pozdrav!")

    elif message.content == "!korisnici":
        online = 0
        idle = 0
        offline = 0

        for m in sentdex_guild.members:
            if str(m.status) == "online":
                online += 1
            if str(m.status) == "offline":
                offline += 1
            else:
                idle += 1
        await message.channel.send(f"""Broj korisnika: {online+offline - 1}\nˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇ\nOnline korisnika: {online - 1}\nOffline korisnika: {offline}\n^^^^^^^^^^^^^^^^^^^^^^^^""") # printa broj korisnika, ali ne broji sebe

    elif message.content == "!ping":
        latency = client.latency
        await message.channel.send(f"""Moj ping iznosi {round(latency, 6)}ms""")

    elif message.content == "!yacketty":
        await message.channel.send("Dostupne komande su: !ping, !bok, !korisnici, !bitcoin...")

    elif message.content == "!bitcoin":
        url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json'
        async with aiohttp.ClientSession() as session:  # Async HTTP request
            raw_response = await session.get(url)
            response = await raw_response.text()
            response = json.loads(response)
            await message.channel.send("Cijena bitcoina: $" + response['bpi']['USD']['rate'])

    elif "!8ball" in message.content:
        moguci_odgovori = [
            'Nema jebene šanse',
            'Možda, ali samo možda',
            'Ahhh, 50-50',
            'Vrlo moguće',
            'Apsolutno da'
        ]
        await message.channel.send(random.choice(moguci_odgovori) + ", " + message.author.mention)

@client.event
async def welcome(member):
    for channel in member.server.channels:
        if str(channel) == "general":
            await client.send_message(f"""{member.mention}, dobrodošao na server!""")

client.run("I'm not showing you this hehe")

1 个答案:

答案 0 :(得分:1)

我看不到您设置authormessages的任何地方。您已将它们设置为全局变量,因此我假设您在调用此函数之前已对其进行设置。如果author是一个空字符串,而messages是0,那么您得到的输出正是我从代码中得到的结果。

由于尚无名为“”的作者,因此它将该作者的条目附加到文件中,该文件为空作者名,冒号和0(即message的值)。

请注意,您的第一个if测试将会成功,并且在此建议的情况下,由于if"" != 0,因此进入了True块。

另一个观察结果……您正在阅读多个现有作者,但您似乎只是将传入的作者与从文件中读取的最后一个作者进行比较。我假设这不是您想要的...您可能想将读取的每个作者与处理文件每一行的循环中传入的作者进行比较。