首页 > 解决方案 > 将 txt 文件的内容作为 dm 发送。不和谐.py

问题描述

你好

我试图让我的不和谐机器人将他从 txt 文件中读出的内容作为 dm 发送给用户。我做了一个命令,它创建一个 txt 文件,该文件应该保护有关用户创建的帐户的一些详细信息。现在我希望用户能够通过在不和谐聊天中发送命令来查看他的帐户详细信息。

进口

import discord
from random import *
from time import *
from discord.ext import tasks
from discord.ext import commands
import asyncio
import os.path

创建文件

@bot.command()
async def join(ctx):
    if os.path.isfile("{}'s Account.txt".format(ctx.author)):
        em=discord.Embed(title="Fail", description="im sorry, but it seems like you already have an account".format(ctx),color=0x992d22)
        await ctx.author.send(embed=em)
    else:
        em=discord.Embed(title="Welcome", description="You have joined the game.\n send !help to see all the commands.".format(ctx),color=0x2ecc71)
        await ctx.author.send(embed=em)
        open("{}'s Account.txt".format(ctx.author), "w+")
        myFile=open("{}'s Account.txt".format(ctx.author), "a")
        myFile.write("Verified! \n  Coins=0 \n  Attack=0 \n Defense=0 \n")

应该向用户发送包含帐户详细信息的 dm

async def credit(ctx):
    Account=open("{}'s Account.txt".format(ctx.author))
    lines = Account.
    em=discord.Embed(title="Balance", description="")
    em.add_field(name="Coins", value="")
    await ctx.author.send(embed=em)
    "{}'s Account.txt".format(ctx.author.close)

我想要达到的目标

命令 collect 应该向用户发送一个包含另外 4 个字段的嵌入字段,其中应该有标题硬币防御和攻击。我希望命令读取相应属性的整数,然后将它们插入具有相应标题的字段中。

标签: pythonfilterintegercommanddiscord.py

解决方案


看起来挺好的!

所以我假设 async 函数credit是一个命令(如果不是@bot.command()在它前面拍 a)。然后与用户创建一个dm,channel = await ctx.author.create_dm()像这样使用和发送;channel.send("Hey bud, sweet dms")

但是你可能已经知道了,所以到好东西上,从文本文件中保存数据,读取它,最后将它放入用户的嵌入中。首先,我会像这样保存数据:Coins,Attack,Defence,这样你就可以轻松恢复数据而无需删除笨拙的单词和东西,因为你知道硬币将在第一位置,攻击将在第二位置,防御将在第三(等等)。

然后,您可以像这样从文本文件中提取数据:

with open(f"{ctx.author}'s Account.txt", "r") as account:
    coins, attack, defence = account.read().split(",")

然后将该信息发送到用户的 dms,如果您愿意,请嵌入:

embed = discord.Embed(title="Account info")
embed.add_field(name="Coins", coins)
embed.add_field(name="Attack", attack)
embed.add_field(name="Defence", defence)
await channel.send(embed=embed)

尖端

  • 保存数据时,我会使用用户的 id,你不希望两个同名的人共享一个帐户
  • 如果您不知道,请在将用户数据保存到文本文件时使用w而不是r

推荐阅读