将 txt 文件的内容作为 dm 发送。 discord.py

sending the content of a txt file as a dm. discord.py

你好

我试图让我的 discord 机器人将他从 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")

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

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 个字段,其中应该有标题硬币防御和攻击。我希望命令读取各个属性的整数,然后将它们插入到具有相应标题的字段中。

看起来不错!

所以我假设异步函数 credit 是一个命令(如果不是在它前面打一个 @bot.command())。然后与用户创建 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