Super -

a year ago
7.2 kB
import nextcord
from nextcord import SlashOption
from nextcord.ui import Select, View
import asyncio
import datetime
from datetime import date
from dateutil.relativedelta import relativedelta

import constants
import gamestats
import apis
import roles
import messages as messagesImport

TOKEN = constants.TOKEN

GuildID = constants.GuildID

intents = nextcord.Intents.default()
intents.members = True

bot = nextcord.Client(intents=intents)

colors = {
    "main": 0x50b7df,
    "error": 0x800000,
    "log": 0x50b7df

channelIDs = {
    "log": 1134441604506193970}

categoryIDs = {

roleIDs = {
    "setRank": 1082385525178122341,
    "staff": 1135490570261893230}

permissionsEmbed = constants.permissionsEmbed

async def on_ready():
    print(f"{bot.user} is now online!")

class gameInfoButtons(nextcord.ui.View):
    def __init__(self):
        emoji = nextcord.PartialEmoji(name="🔗")
  , url=constants.GameLink, label="Link", disabled=False, emoji=emoji))

@bot.slash_command(guild_ids=[GuildID], description="Get the information about a game")
async def gameinfo(interaction: nextcord.Interaction):
    gameStats = gamestats.getStats()

    embed = nextcord.Embed(title="Game Statistics", description=f"""
**Playing: ** {gameStats['playing']}        
**Visits: ** {gameStats['visits']}
**Favorites: ** {gameStats['favorited']}                   
**Up votes: ** {gameStats['upvotes']}
**Down votes: ** {gameStats['downvotes']}
""", color=colors['main'])
    view = gameInfoButtons()
    await interaction.response.send_message(embed=embed, view=view)

# Roles

@bot.slash_command(guild_ids=[GuildID], description="Set a users rank in the group")
async def setrank(interaction: nextcord.Interaction, username: str):
    if interaction.user.get_role(roleIDs['setRank']):
        userID = apis.getID(username)
        if userID:
            # deferredInteraction = await interaction.response.defer()
            if apis.isGroupMember(userID):
                async def channelCallback(cbinteraction):
                    for value in dropdownForHire.values:
                        groupRank = apis.getGroupRank(userID)
                        if groupRank['rank'] == int(value):
                            embed = nextcord.Embed(
                                title="Same rank", description="You cannot change the users rank to be the same as it already is.", color=colors['error'])
                            await viewInteraction.edit(embed=embed, view=None)
                            setRankResponse = await roles.setRank(username, int(value))
                            if setRankResponse:
                                groupRank = apis.getGroupRank(userID)
                                embed = nextcord.Embed(
                                    title=f"{username}'s rank has been changed to {groupRank['name']}", description=f"{username}'s rank has been changed to {groupRank['name']} by <@{}>", color=colors['main'])
                                await viewInteraction.edit(embed=embed, view=None)
                options = constants.setRankOptions
                dropdownForHire = Select(
                    placeholder="What rank to set the user to?", options=options, max_values=1)
                dropdownForHire.callback = channelCallback
                rankView = View(timeout=None)
                embed = nextcord.Embed(
                    title="Change user rank", description="Please choose what rank to role the user below.", color=colors['main'])
                viewInteraction = await interaction.response.send_message(embed=embed, view=rankView)
                embed = nextcord.Embed(
                    title="User not in group", description="The user is not in the group. Please make sure they are in it and try again.")
                await interaction.response.send_message(embed=embed, ephemeral=True)
            embed = nextcord.Embed(
                title="User not found", description="Please check that the username is correct and try again later.")
            await interaction.response.send_message(embed=embed, ephemeral=True)
        await interaction.response.send_message(permissionsEmbed)

@bot.slash_command(guild_ids=[GuildID], description="Get the messages leaderboard")
async def leaderboard(interaction: nextcord.Interaction):
    leaderboardDict = messages.getLeaderboard()
    descriptionText = ""
    for key in leaderboardDict:
        descriptionText = descriptionText + \
            f"<@{key}>: `{leaderboardDict[key]}` messages \n"
    embed = nextcord.Embed(title="Messages Leaderboard",
                           description=descriptionText, color=colors['main'])
    await interaction.response.send_message(embed=embed)

@bot.slash_command(guild_ids=[GuildID], description="Message history")
async def messages(interaction: nextcord.Interaction, timeframe: str = SlashOption(
    description="Choose the time from which you want to see messages",
    choices=["Weekly", "BiWeekly", "Monthly",
             "3-Months", "6-Months", "Yearly", "All time"],
    guild = bot.get_guild(GuildID)
    channel = guild.get_channel(1134441604506193970)
    messagesDict = {}
    afterTime = datetime.datetime.utcnow()
    if timeframe == "Weekly":
        afterTime = afterTime - datetime.timedelta(weeks=1)
    elif timeframe == "BiWeekly":
        afterTime = afterTime - datetime.timedelta(weeks=2)
    elif timeframe == "Monthly":
        afterTime = afterTime - relativedelta(months=1)
    elif timeframe == "3-Months":
        afterTime = afterTime - relativedelta(months=3)
    elif timeframe == "6-Months":
        afterTime = afterTime - relativedelta(months=6)
    elif timeframe == "Yearly":
        afterTime = afterTime - relativedelta(years=1)
    elif timeframe == "All time":
        afterTime = None

    async for message in channel.history(limit=None, after=afterTime):
        userID = str(
        if userID in messagesDict:
            messagesDict[userID] += 1
            messagesDict[userID] = 1

    finalText = ""
    sortedDict = messagesImport.sortMessages(messagesDict)
    for item in sortedDict:
        finalText += f"<@{str(item)}>: {sortedDict[item]} \n"

    staffRole = guild.get_role(roleIDs['staff'])
    for user in staffRole.members:
        if not str( in sortedDict:
            finalText += f"<@{str(}>: 0 \n"

    embed = nextcord.Embed(
        title=f"{timeframe} User messages", description=finalText, color=colors['main'])
    await interaction.response.send_message(embed=embed)