python – Discord.py pages for a leaderboard

So I’ve got a Discord bot that will load information about a user’s personal charts and display it to them, and one of the commands is to get their leaderboard and show them the most successful songs on their charts. It does this by creating different pages in the embed, and the user can press the reactions to change pages. However, when it comes to generating the embed for each page, I feel like the code I’m using is very messy and could be done in a loop instead, but I’m just not quite sure how to do that, so I’d much appreciate some feedback.

description = ()
for i, _ in enumerate(song_name): #song_name is a list of the names of all the songs on the leaderboard
    if i >= 0 and i < 10:
        try:
            description(0) = description(0) + "n" + str(i+1) + ". **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)"
        except IndexError:
            description.append("1. **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)")
    if i >= 10 and i < 20:
        try:
            description(1) = description(1) + "n" + str(i+1) + ". **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)"
        except IndexError:
            description.append("11. **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)")
    if i >= 20 and i < 30:
        try:
            description(2) = description(2) + "n" + str(i+1) + ". **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)"
        except IndexError:
            description.append("21. **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)")
    if i >= 30 and i < 40:
        try:
            description(3) = description(3) + "n" + str(i+1) + ". **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)"
        except IndexError:
            description.append("31. **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)")
    if i >= 40 and i < 50:
        try:
            description(4) = description(4) + "n" + str(i+1) + ". **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)"
        except IndexError:
            description.append("41. **" + song_artists(i) + "** - **(" + song_name(i) + ")(" + song_link(i) + ")** (" + f"{int(song_points(i)):,}" + " points)")

discord.py – In embed.fields.0.value: This field is required error

@client.command()
async def hug(ctx, *, user: discord.Member = None):

    hug_embed = discord.Embed(title='-w- hug -w-', description='', color=0xafe8fa)
    hug_embed.add_field(name=f'{ctx.author.mention} hugged {user.mention}', value='', inline=False)

    if user:
        await ctx.message.channel.send(embed=hug_embed)
    else:
        await ctx.send('hug someone ;n;')

I got the error of
In embed.fields.0.value: This field is required

how do i mention another person, with it sending in an embed response

python – Discord.py Task Loop Running Too Often and Not Completing

I’m currently running into an issue with Discord.py where I have a task loop which keeps reiterating instantly without actually finishing. Below you can find a snippet of my code.

import discord
from discord.ext import commands, tasks
import insider

@client.event
async def on_ready():
    print("Bot is Ready.")
    check_insider_activity.start()

@tasks.loop(minutes=5)
async def check_insider_activity():
    print("Checking Insider Buys")
    newBuys = insider.get_new_insider_buys()
    print(newBuys)

Whenever I run my code, the output is as follows :

Bot is ready.
Checking Insider Buys
Checking Insider Buys
Checking Insider Buys
Checking Insider Buys
Checking Insider Buys
Checking Insider Buys

It sends “Checking Insider Buys” roughly every second or two, and keeps on doing that until I exit the program. The function get_new_insider_buys() never seems to complete, and I never get to the print statement before the task seems to just restart.

For some context, get_new_insider_buys() is a function which returns a list of new insider buys. The function scrapes a webpage using BeautifulSoup and manipulates some data using a Pandas Dataframe, then writes it to a local file before returning a list.

get_new_insider_buys() runs perfectly on its own, but as soon as I want to put it into the Discord.py task loop, it never seems to execute.

I feel as though I’ve got some form of concurrency or task error happening within the function, though I don’t know how or why, and I’m at my wits end. I can get other tasks working just fine, but as soon as I add this one to the mix, it all breaks, and all of my tasks start behaving like this one.

python – Discord.py Bot : Sends with the loverate between 2 persons

I’m creating a Discord Bot and i made a !love command which is testing the love rate between 2 persons or entities.

Example : !love Peignoir Emma

Result: The loverate between Peignoir and Emma is x%

Here’s the code :

@bot.command(name="love", aliases=("l"))
async def love(ctx, Personne1, Personne2):
    if ctx.message.channel.id != 763352957579690018:
        printIt = 1
        wordBanList = ('@everyone', '@here', '<@&763489250162507809>','<@&777564025432965121>','<@&822200827347075132>',
                       '<@&763815680306184242>','<@&764422266560839680<','<@&763815728972300338>','<@&763815728972300338>',
                       '<@&763815228323528725>','<@&763815784904261632>','<@&764422166116171806>','<@&764422057353936897>',
                       '<@&804807279043674143>','<@&828664814678179861>','<@&823562218095640646>','<@&823638574809219163>')
        LoveRate = str(random.randrange(0, 100))
        for y in range(len(wordBanList)):
            if(Personne1 == wordBanList(y) or Personne2 == wordBanList(y)):
                printIt = 0

        if(printIt == 0):
            await ctx.send("Tu t'es pris pour qui ?")
            if debug == True:
                print("(DEBUG) !love : Someone tried to use a banned word !")
        else:
            await ctx.send("L'amour entre **"+Personne1+"** et **"+Personne2+"** est de **"+LoveRate+"%** <:flushed:830502924479758356>")
            if debug == True:
                print("(DEBUG) !love : The love rate ("+LoveRate+"%) between "+Personne1+" and "+Personne2+" has been printed in channel ID "+str(ctx.channel.id))
    else:
        botChannel = discord.utils.get(ctx.guild.channels, id=768194273970880533)
        messageBot = await ctx.send("Va faire cette commande dans "+botChannel.mention+" ou je te soulève <:rage:831149184895811614>")
        await asyncio.sleep(5)
        await ctx.message.delete()
        await messageBot.delete()

I’m pretty sure this code is optimizable, but i don’t know how, can somebody help me 🙂 ?

python – How would I get a role from a role mention with discord.py?

I am wondering how I would get a role from a role mention in discord.py. I have a command that requires one of the arguments to be a mentioned role, for example if my bot prefix was *, *giverole @user @role. Is there a way to do this? I know you can do that for a user with member : discord.Member. Thanks in advance if you help. Sorry if this sounded vague its kind of hard to explain (for me)

python – Discordpy como pegar o nome e não a referencia ao objeto

Olá! Estou brincando um pouco com a biblioteca Discord no python, mas cheguei num problema.

Quando quero pegar o nome do usuário que mandou a mensagem, e o id e creio que tudo que faça referência aos dados do usuário o formato que volta é como se estivesse usando repr e não print.

Esse é o código que tenho

import discord
from discord.ext import commands
    
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='dia-', description=description, intents=intents)

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('-*-*-*-*-*-*-*-*-*-')

@bot.command()  
async def info(ctx, user = discord.Member):  
    await ctx.send(f'{user.mention}'s id: `{user.id}`') 

bot.run('token')

Quando vou para o discord e uso o prefixo “dia-” e coloco o commando “info” (dia-info) essa é a saída que tenho no discord

<property object at 0x000001C8E4F2ACC0>'s id: <property object at 0x000001C8E4F342C0>

Gostaria que aparecesse o meu nome e id no discord, mas não faço ideia de como proceder!
Desde já grato!

python – accessing dictionaries in discord.py

Basically I want to make a help command for my discord bot in python that uses a dictionary. I’m not done with it yet, and the code for now looks something like this:

helpdict = {
  'command1': ('description', 'usage', 'aliases'),
  'command1': ('description', 'usage', 'aliases'),
  #and so on...
}

@commands.command()
async def help(self, ctx, cmd=None):

  if cmd == None:
    await ctx.send(helpdict.keys())

The problem is I get an error saying that helpdict is undefined, no matter how i use it. Can someone tell me what I’m doing wrong? (btw the code is written in a cog with proper initializing)