【发布时间】:2021-10-13 09:55:30
【问题描述】:
我被卡住了,一直在查看文档,但没有什么清楚地跳出来。 我要做的是让我的机器人在指定范围内加载消息,并计算特定定义短语的出现次数。
例如。 短语=“货车” !phrase 5 - 返回过去 5 天内的所有消息 然后返回过去 5 天内“wagons”被提及的次数
""" Simple program for the bot to return information about the guild """
import os
import datetime as dt
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv() # loads the encapsulated values from the .env file
# Declaration of Encapsulated Variables
TOKEN = os.getenv('BOT_TOKEN')
TESTING_GUILD_KEY = os.getenv('TESTING_GUILD_KEY')
TESTING_CHANNEL = os.getenv('TESTING_CHANNEL')
# Declaration of Discord.py Intents
intents = discord.Intents.default() # Turns on the connection
intents.members = True # Ensures the member list will be updated properly
client = discord.Client(intents=intents) # captures the connection to discord
# Declaration of Discord.py Variables
guild_key = client.get_guild(int(TESTING_GUILD_KEY))
bot = commands.Bot(command_prefix='!')
@client.event
async def on_message(message):
""" Defines events for which the bot will return information by the user typing commands """
all_members = get_all_members() # has all the members visible to the bot
# Sends to the channel the event is called, the total amount of users in the guild
if message.content.find("!userCount") != -1:
await message.channel.send(f"""We currently have {len(all_members)} members in the server""")
# Sends to the channel the event is called, a list of users currently in the guild
elif message.content.startswith('!member'):
await message.channel.send(f"""The current member list is: \n""")
for each_member in all_members:
await message.channel.send(f"""- {each_member}""")
def get_all_members():
""" Returns A list of users currently in the server """
list_of_members = [] # Declaration of Empty Dictionary
# Declaration of logic to print out each user in the guild
for each_guild in client.guilds:
for each_member in each_guild.members:
list_of_members.append(each_member) # adds the member
return list_of_members
# @client.event
# async def keyword(ctx, word):
# channel = client.get_channel(int(TESTING_CHANNEL))
# messages = await ctx.channel.history(limit=200).flatten()
# count = 0
#
# for msg in messages:
# if word in msg.content:
# count += 1
# print(count)
@bot.command()
async def something(ctx):
pass
@bot.command()
async def find(ctx, days: int = None, phrase: str = None):
if days and phrase:
after_date = dt.datetime.utcnow() - dt.timedelta(days=days)
# limit can be changed to None but that this would make it a slow operation.
messages = await ctx.channel.history(limit=10, oldest_first=True, after=after_date).flatten()
# loop each message to check for phrase
for message in messages:
if phrase in message.content:
print(message)
else:
await ctx.send("please enter the number of days wanted")
client.run(TOKEN)
我认为我使用短语功能很接近,但是它无法正常工作。不确定我是否必须打开意图,或者代码中是否缺少某些内容。 感谢您的帮助!
【问题讨论】:
标签: python discord discord.py message