Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

迁移EDGY程序到框架中 #4

Open
retr0-init opened this issue Feb 18, 2024 · 0 comments
Open

迁移EDGY程序到框架中 #4

retr0-init opened this issue Feb 18, 2024 · 0 comments

Comments

@retr0-init
Copy link
Owner

import logging
import discord
from discord.ext import tasks, commands
from datetime import datetime
import json

BotToken = 'xxxxxxxxxxxxxxxxxxxx111111111111111111111111111'
intents = discord.Intents.all()
client = commands.Bot(command_prefix='/', intents=intents)

GUILD_ID = 1234567890
FORUM_ID_TO_MONITOR = 1234567890

UPPER_LIMIT = 100


# This function takes the global constant, GUILD_ID and FORUM_ID_TO_MONITOR, and returns a temp_forum object( by discord.py
# standard) as the target to be monitored here.
def align_target_forum():
    temp_guild = None
    temp_forum = None

    for aGuild in client.guilds:
        if aGuild.id == GUILD_ID:
            temp_guild = aGuild

    for aForum in temp_guild.forums:
        if aForum.id == FORUM_ID_TO_MONITOR:
            temp_forum = aForum

    if temp_forum is None:
        print('Forum not found!')
    else:
        return temp_forum


# A class to represent a valid member-thread interaction, notice that any interactions by the same member will be considered
# as one valid interaction, as a member could only agree/disagree once toward the same topic/proposal. Before this proposal
# system is applied, both message and reaction(emoji) replies would be count once as well.
class ValidInteractionInThread:
    def __init__(self, thread_id, member_id):
        self.thread_id = thread_id
        self.member_id = member_id

    def __eq__(self, other):
        if isinstance(other, ValidInteractionInThread):
            return self.thread_id == other.thread_id and self.member_id == other.member_id
        return False


async def get_current_valid_interactions_list(target_forum):
    temp_valid_interactions_list = []

    temp_all_threads = target_forum.threads

    for aThread in temp_all_threads:
        # Append members that have interacted by sending a message
        temp_all_message_member_in_thread = await aThread.fetch_members()
        for aMember in temp_all_message_member_in_thread:
            temp_valid_interaction = ValidInteractionInThread(aThread.id, aMember.id)
            if temp_valid_interaction not in temp_valid_interactions_list:
                temp_valid_interactions_list.append(temp_valid_interaction)

        # Append members that have interacted by sending a reaction(emoji)
        temp_all_messages_within_thread = [message async for message in aThread.history()]
        temp_all_reactions_within_thread = []

        for aMessage in temp_all_messages_within_thread:
            temp_all_reactions_within_thread.append(aMessage.reactions)

        for aReactions in temp_all_reactions_within_thread:
            for aReaction in aReactions:
                users = [user async for user in aReaction.users()]
                for aUser in users:
                    temp_valid_interaction = ValidInteractionInThread(aThread.id, aUser.id)
                    if temp_valid_interaction not in temp_valid_interactions_list:
                        temp_valid_interactions_list.append(temp_valid_interaction)

    return temp_valid_interactions_list


# Below is a list storing all valid interactions found since bot start running.
past_valid_interactions_list = []
# A list storing the numbers of interactions newly found during EACH loop period, in int format, since bot start running.
interactions_count_history = []
# A list storing all the recording datetime information, in str format, of EACH update.
datetime_strings = []


# hours=24
# A task which loops every day, updating newly found interactions.
@tasks.loop(seconds=10)
async def update_valid_interaction_daily(target_forum):
    current_time = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    datetime_strings.append(current_time)

    global past_valid_interactions_list

    if len(past_valid_interactions_list) == 0:
        past_valid_interactions_list = await get_current_valid_interactions_list(target_forum)
        interactions_count_history.append(len(past_valid_interactions_list))
    else:
        current_valid_interactions_list = await get_current_valid_interactions_list(target_forum)
        temp_valid_interactions_count = 0
        for aInteraction in current_valid_interactions_list:
            if aInteraction not in past_valid_interactions_list:
                past_valid_interactions_list.append(aInteraction)
                temp_valid_interactions_count += 1
        interactions_count_history.append(temp_valid_interactions_count)

    while len(interactions_count_history) < len(datetime_strings):
        interactions_count_history.append(0)

    while len(interactions_count_history) > UPPER_LIMIT:
        interactions_count_history.pop(0)
        datetime_strings.pop(0)

    interaction_wrt_time = {'datetime_strings': datetime_strings, 'interactions_count_history': interactions_count_history}

    with open('Data/ForumActivitiesHistory/Interaction_WRT_Time.json', 'w') as f:
        json.dump(interaction_wrt_time, f)
    print(interactions_count_history, datetime_strings)


@client.command(name='forum_activities', description='get the last few days\' activities w.r.t time')
async def forum_activities(ctx):
    with open('Data/ForumActivitiesHistory/Interaction_WRT_Time.json', 'r') as f:
        interaction_wrt_time = json.load(f)

    temp_datetime_strings = interaction_wrt_time['datetime_strings']
    temp_interactions_count_history = interaction_wrt_time['interactions_count_history']

    output_str = ''

    if len(temp_datetime_strings) > 10:
        for i in range(10, 0,-1):
            output_str += 'Activities found at ' + temp_datetime_strings[-i] + ' is:'+str(temp_interactions_count_history[-i])
    else:
        for i in range(0,len(temp_datetime_strings)):
            output_str += 'Activities found at ' + temp_datetime_strings[i] + ' is:'+str(temp_interactions_count_history[i])


    await ctx.send(output_str)


@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')
    target_forum = align_target_forum()
    update_valid_interaction_daily.start(target_forum)


client.run(BotToken)
@retr0-init retr0-init moved this from 预备 to 垃圾箱 in Discord机器人开发Kanban Feb 28, 2024
@retr0-init retr0-init moved this from 垃圾箱 to 预备 in Discord机器人开发Kanban Apr 21, 2024
@retr0-init retr0-init moved this from 预备 to 垃圾箱 in Discord机器人开发Kanban Apr 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: 垃圾箱
Development

No branches or pull requests

1 participant