【问题标题】:Trouble with getting total messages in Discord.Py在 Discord.Py 中获取总消息的问题
【发布时间】:2021-06-30 18:17:39
【问题描述】:

所以,在过去的一个小时左右,我一直在摸不着头脑,将所有文本通道中的所有消息都保存到 CSV 文件中。除了粗体部分之外,其他一切都很好。

编辑:好吧,如果您放入代码示例中,它不会显示粗体部分。所以我会删除它。

我知道 API 文档中提到了该方法:

counter = 0
async for message in channel.history(limit=200):
    if message.author == client.user:
        counter += 1

另外,没有提到它,但如果我单独做,它确实有效,我从另一篇文章中获得的代码,有点挑剔,因为我只和一个用户一起做过。

这是我让它工作的命令:

@bot.command(name="message")
async def get_messages(ctx):
    userMessages = []
    userID = 123456# Change this to the ID of the user you are looking messages for
    channelID = 7890123# Change this to the channel ID of the messages you want to check for

    channel = bot.get_channel(channelID)
    user = discord.utils.find(lambda m: m.id== userID, channel.guild.members)
    
    counter = 0
    async for message in channel.history(limit=):
        print(channel.name)
        if message.author == user:
            counter += 1

    print(counter)

但我似乎无法在我的脚本中实现它。

这是我的命令:

# bot.py
import os
import random
import discord
import csv
import io
import datetime


from discord.ext import commands
from dotenv import load_dotenv

intents = discord.Intents.default()
intents.members = True  # Subscribe to the privileged members intent.
intents.messages = True  # Subscribe to the privileged members intent.

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

month = datetime.datetime.now() - datetime.timedelta(days=1)

bot = commands.Bot(command_prefix='&', intents=intents)
@bot.command(name="lista",help="Creates member list")
async def get_members(ctx):
    file = 'log.csv'     
    await ctx.message.delete()
    with io.open(file, "w", encoding="utf-8",newline='') as output:
        writer = csv.writer(output)
        writer.writerow(['list of roles']
        includeChannels = ['list of channels']
        for guild in bot.guilds:            
            for member in ctx.guild.members:
                roles = []
                for role in member.roles:
                    exists = role.name in excludeRoles
                    if exists == False:
                        roles.append(role.name)
                    f = ' '.join(roles)                
                for channel in ctx.guild.text_channels:
                    async for message in channel.history():
                        if message.author == str(member):
                            a = "okay"
                writer.writerow([str(member),member.display_name,member.joined_at.strftime("%d-%m-%Y"),f,a])

bot.run(TOKEN)

我得到的错误是 403 禁止(错误代码:50013):缺少权限。

编辑 2: 好吧,感谢@makonede,我能够不显示错误,但是,我似乎无法获得计数器,即使我已经实际测试过 message.author 和 user 都显示为同样,使用名称#id,我将计数器命令分成了一个新命令,只是为了在问题中得到更多关注,它会上升到最后一个 if,但从不进入它的内部进行计数器。也许我缺少一些东西,但是,我很难过:

@bot.command(name="message",help="Creates member list")
async def history(ctx):
  includeChannels = ['family-chat', 'children-only-chat', 'pictures', 'food', 'support-hype','babies-and-toddlers-chat']
  await ctx.message.delete()    
  for guild in bot.guilds:
    for member in ctx.guild.members:
      counter = 0
      for channel in guild.text_channels:
        exists = channel.name in includeChannels
        if exists == True:
          try:
            async for message in channel.history(limit=100,after=month):
              if str(bot.user) == str(message.author):
                counter+=1
          except discord.Forbidden:
            pass
          print(counter)

【问题讨论】:

  • 请发布完整回溯,而不仅仅是其中的一部分。
  • @ŁukaszKwieciński 完成
  • @RafaelHernandez 我仍然没有看到完整的回溯...“我得到的错误是 403 禁止的 50001。”不是完整的回溯。
  • 对不起 >_
  • 这个错误实际上是不言自明的。您的机器人似乎没有必要的频道访问权限。

标签: python python-3.x discord.py


【解决方案1】:

您的机器人有权访问的其中一个服务器中的一个文本通道已为该机器人禁用了读取消息历史记录。简单的错误处理就可以解决问题:

try:
    async for message in channel.history():
        if message.author == str(member):
            a = "okay"
except discord.Forbidden:
    pass

【讨论】:

  • 这行得通,谢谢! ,我做了更改,它似乎确实有效,但是,现在它似乎没有添加计数器,我已经编辑了我的原始帖子,并在最后一部分分开。
【解决方案2】:

好的,经过一周的尝试,我已经解决了这个问题。我更改了一些初始代码,因为如果我在另一台服务器上安装机器人,它会使用户翻倍,所以这就是我想要的。所以,这里是代码:

@bot.command(name="log",help="Sends a list of members, with roles, and join date")
async def get_members(ctx):
    file = 'log.csv'
    await ctx.message.delete()    
    with io.open(file, "w", encoding="utf-8",newline='') as output:
        writer = csv.writer(output)
        writer.writerow(['Name','Server Name','Joined At','Roles','ID','Messages'])
        excludeRoles = ['roles']        
        channel = bot.get_channel(788762422050553867)
        messages = await channel.history(limit=None,after=sunday).flatten()
        for member in ctx.guild.members:
            roles = []
            counter = 0
            for role in member.roles:
                exists = role.name in excludeRoles
                if exists == False:
                    roles.append(role.name)
                f = ' '.join(roles)
            for message in messages:
                if message.author == member:
                    counter+=1
            writer.writerow([str(member),member.display_name,member.joined_at.strftime("%d-%m-%Y"),f,'id: '+str(member.id),counter])
                
        await ctx.send(file=discord.File(fp='log.csv'), content="Here is the list of members that are on the discord, with their joined dates and roles, and how many messages have they sent in #support-hype")

它的作用是提取名称、服务器名称、他们何时加入、他们的角色以及他们最终在特定频道中发送了多少消息。

【讨论】:

    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2019-04-21
    • 1970-01-01
    • 2021-05-06
    • 2020-07-27
    • 2021-01-28
    相关资源
    最近更新 更多