#discord-bots

1 messages · Page 190 of 1

brazen raft
#

Since when is it in the standard library

glad cradle
slate swan
#

requests is not a stdlib package, that's urllib.requests, requests is 3rd party

#

!d urllib.request

unkempt canyonBOT
slate swan
#

It is

cloud dawn
#

I mean makes sense since mimetype need the actual file.

#

Also mimetypes won't "guess", it's a way to verify an extension reliably.

potent light
cloud dawn
#

Finally I can get a reaction in this channel.

lament mesa
#

😬

lament mesa
#

this channel has got fairly inactive after Aug 28, 2021

lament mesa
#

what are those random spikes

cloud dawn
# lament mesa what are those random spikes

Well those spikes since the X axis is so small in comparison to the timeline. Those are most likely public holidays. Since most people here are younger than the rest of the average age.

#

Could be numerous things.

lament mesa
#

no i meant the spikes in the messages count

#

after october

cloud dawn
lament mesa
lament mesa
heady verge
#
    @slash_command(name='giveaway')
    async def giveaway(self, interaction: Interaction):
        return

    @giveaway.subcommand(name='start')
    ...

AttributeError: 'SlashCommand' object has no attribute 'subcommand'. Did you mean: 'is_subcommand'?
i am using pycord

unkempt canyonBOT
#

examples/app_commands/slash_groups.py lines 14 to 20

math = discord.SlashCommandGroup("math", "Commands related to mathematics.")


@math.command()  # Create a slash command under the math group
async def add(ctx: discord.ApplicationContext, num1: int, num2: int):
    """Get the sum of 2 integers."""
    await ctx.respond(f"The sum of these numbers is **{num1+num2}**")```
young dagger
#

Can you make embeds without value field?

    embed = discord.Embed(title="![check_mark](https://cdn.discordapp.com/emojis/1061670706275942420.webp?size=128 "check_mark") Please wait while the bot is balancing the teams.", color=discord.Color.black())
    message = await ctx.send(embed=embed)```
slate swan
#

no

#

why don't you just use the description?

#

also, you can use an empty field add_field(name="name", value="\u200b")

waxen obsidian
#

I have a cog and for some reason it doesn't connect to the main, can someone help me please?

young dagger
#

Unresolved attribute reference 'black' for class 'Colour'

#

Black doesn't exist? 🤔

#

Should I just use discord.Color.default?

hushed galleon
#

discord.Color(0) would work too, or 0

young dagger
hushed galleon
#

!d discord.Colour.default

unkempt canyonBOT
#

classmethod default()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0`.
hushed galleon
#

0 as in the hex value 0x000000, meaning 0 red, 0 green, and 0 blue, so black

young dagger
#

What is wrong with this code?

            # Check if the user is already in the queue
            if member not in queue:
                # Add the user to the queue
                queue.append(member)
                # Send a message to the channel
                channel = discord.utils.get(member.guild.text_channels, id=712074759453671494)
                embed = discord.Embed(title=f'{len(queue)} players are currently in the queue',
                                      description=f'{member.mention} has been added to the queue.',
                                      timestamp=datetime.datetime.now(), color=discord.Color.blue())
                await channel.send(embed=embed)```
#

I can't use await channel.send(embed=embed)?

naive briar
#

What's the problem with it

young dagger
#

I'm getting Unexpected argument and Parameter '__value' unfilled

slate swan
#

show full traceback

maiden fable
slate swan
#
channel = discord.utils.get(member.guild.text_channels, id=712074759453671494)``` ❎ 
```py
channel = guild.get_channel(712074759453671494)
slate swan
young dagger
#

Thanks

shrewd fjord
#

Living ded found

heavy belfry
#

please help, i get this error when trying to load another file from a folder: bot.load_extension("Mining_bot_commands.Mining_help")

discord.ext.commands.errors.ExtensionFailed: Extension 'Mining_bot_commands.Mining_help' raised an error: TypeError: The command passed must be a subclass of Command

OHH i named a variable badly

untold mountain
#

How to fix this

File "C:\Users\user\Downloads\Anya bot pls work\main.py", line 9, in <module>
bot = commands.Bot (command_prefix='/')
TypeError: BotBase.init() missing 1 required keyword-only argument: 'intents'

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

whole sparrow
#

Is there a way to change position of voice channel using bot?

quick gust
#

i dont believe so

maiden fable
#

VCs are always shown at the last

quick gust
#

I think they meant the order of the VCs in itself but yeah the answer is still no

vocal snow
#

!d discord.abc.GuildChannel.move

unkempt canyonBOT
#

await move(**kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A rich interface to help move a channel relative to other channels.

If exact position movement is required, `edit` should be used instead.

You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.

Note

Voice channels will always be sorted below text channels. This is a Discord limitation...
sick birch
#

Note the note

vocal snow
#

They will be behind the text channels but can me re-ordered within themselves ig

feral timber
#

@sick birch BTW

#

Get to work

sick birch
#

Go fuck yourself

verbal hawk
#

Hi yall! I'm making a ticket system, and I have a problem with a piece of code that ensures that a user can't create multiple tickets in the same category.
Code:

`existing_channels = [channel for channel in guild.text_channels if channel.name.startswith(f"{category}-{author}")]
if existing_channels:
    ticketwarn = await ctx.send(f"You already have a  `{category}`  ticket open, please use that instead! {user.mention}!")
    await asyncio.sleep(3)
    await ticketwarn.delete()
    return`

this is before it creates a text channel btw
the ticket channel name format is {category}-{author}
However it does not prevent me from creating multiple tickets in the same category. What could be the issue with it?

sick birch
verbal hawk
# sick birch Can we see where author and category are defined?

a category and a user variables are passed to the tickethandler function, I get author by doing author = str(user)[:-5], the category is defined in the function that listens for reaction, and is passed like this:

  if reaction.emoji == "1️⃣":
            category = "Owner"
        elif reaction.emoji == "2️⃣":
            category = "Donate"
        elif reaction.emoji == "3️⃣":
            category = "Other"
        await message.remove_reaction(reaction.emoji, user)
        asyncio.create_task(tickethandler(ctx, category, user))

both category and user are correct, because they are used in the title of the ticket channel

#

I tried printing the category and the author variables for debug but they are correct, and are what they are supposed to be

young dagger
#

How can I solve the error message Local variable 'thumbnail_url' might be referenced before assignment?

                   for rank, url in rank_to_thumbnail.items():
                        if tier_and_rank.startswith(rank):
                            thumbnail_url = url
                            break

                    if thumbnail_url:
                        embed.set_thumbnail(url=thumbnail_url)
                    await ctx.channel.send(embed=embed)```
#

I'm getting the error because its inside the loop

#

thumbnail_url

golden portal
young dagger
# golden portal this error happens when `thumbnail_url` might not be defined by the time you're ...

Thanks. How can I make this code easier to understand?

                    rank_to_thumbnail = {
                        "Iron": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-iron.png",
                        "Bronze": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-bronze.png",
                        "Silver": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-silver.png",
                        "Gold": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-gold.png",
                        "Platinum": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-platinum.png",
                        "Diamond": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-diamond.png",
                        "Master": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-master.png",
                        "Grandmaster": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-grandmaster.png",
                        "Challenger": "https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-challenger.png",
                    }
                    thumbnail_url = None
                    for rank, url in rank_to_thumbnail.items():
                        if tier_and_rank.startswith(rank):
                            thumbnail_url = url
                            break

                    if thumbnail_url:
                        embed.set_thumbnail(url=thumbnail_url)
                    await ctx.channel.send(embed=embed)```
golden portal
#

um

#

whats the example string for tier_and_rank? ThinkO_O

#

whats the point of that dict if you're gonna iterate through it

young dagger
#

Can't I use thumbnail_url = https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/{grab_from_the_list}.png

#

Then use emblem-challenger if starts with Challenger

young dagger
golden portal
#

oh, couldn't you just split it then by space, get the first word

young dagger
#

Tier = Iron-Challenger
Rank = 1-4

vocal snow
#

You should just get the first word and use a dictionary lookup then

golden portal
#

i dont think dict a necessary, could just lower the word, and then do f-string with the url

vocal snow
#

Yes the URLs are very conveniently named

#

But if you're in a situation where you're using a dictionary solely for iteration, chances are you should use a list of tuples instead, dicts consume much more memory

golden portal
# young dagger Silver 1, Silver 2, Gold 4 etc

since the pattern is like that, you can use str.partition with space, lower it, then f-string with your url, ```py
rank, *_ = tier_and_rank.partition(" ") # first occurance split
lowered_rank = rank.lower() # lower-case
url = f'https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-static-assets/global/default/images/ranked-emblem/emblem-{lowered_rank}.png' # basic f-string

should be fine since the only thing i see that changes in your url is the name
young dagger
golden portal
#

the if statement is kinda redundant since its always gonna be truthy

young dagger
golden portal
#

yea you might wanna check the rank instead of thumbnail_url if thats the case

golden portal
# young dagger How do I do that?

check if the rank are valid in your predicate? its totally up to you, i dont know every single thing about your 'rank' unfortunately

young dagger
#
if lowered_rank == 'unranked':
    pass```
young dagger
golden portal
#

doing if-else is not pretty

young dagger
#

Understood

#

Thanks @golden portal

golden portal
#

welcome

young dagger
#

Anyone know why I got this error message? It seems like I only got it once and I can't figure out why. discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'get_role'

                    # Get the custom games role
                    custom_games_role = ctx.guild.get_role(712084626201641070)
                    # Add the custom games role to the user
                    await user.add_roles(custom_games_role)```
golden portal
young dagger
slate swan
golden portal
slate swan
#

I'd like to do the filter before py for ... In ... Because if the bot doesn't find a .jpg image it retries

young dagger
#

AttributeError: 'function' object has no attribute 'guild_only'

young dagger
golden portal
#

yes

slate swan
#

someo'e can help me to filtrer the image the bot have to scrape

young dagger
# golden portal yes

@commands.guild_only()
AttributeError: 'Command' object has no attribute 'guild_only'

golden portal
#

alternatively you should name your function as something else and use name kwarg to rename, py @client.command(name='commands') async def _commands(...): that way it doesnt overshadow your discord.ext.commands

young dagger
golden portal
#

ye

#

truthfully i would handle commands.CheckFailure and show the error directly to the user, this cover for all check errors

pseudo saffron
#

hey i need some help
TypeError: cogs must derive from Cog

import discord
from discord.ext import commands
import json
import os
import asyncio

# Get configuration.json
with open("configuration.json", "r") as config: 
    data = json.load(config)
    token = data["token"]
    prefix = data["prefix"]
    owner_id = data["owner_id"]


intents = discord.Intents.default()
bot = commands.Bot(prefix, intents = intents, owner_id = owner_id)

async def loadcogs():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main():
    await loadcogs()
    await bot.start(token)

asyncio.run(main())```

```py
import discord
from discord.ext import commands



class misc(commands.Cog):
    def __init__(self,bot):
        self.bot = bot

    @commands.command()
    async def ping(self,ctx):
        await ctx.send('pong')






async def setup(bot):
    await bot.add(misc)
pseudo saffron
#

Exception has occurred: ExtensionFailed
Extension 'cogs.misc' raised an error: TypeError: cogs must derive from Cog
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\cogs\misc.py", line 21, in setup
await bot.add_cog(misc)
TypeError: cogs must derive from Cog

The above exception was the direct cause of the following exception:

File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\main.py", line 21, in loadcogs
await bot.load_extension(f'cogs.{filename[:-3]}')
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\main.py", line 24, in main
await loadcogs()
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\main.py", line 27, in <module>
asyncio.run(main())
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.misc' raised an error: TypeError: cogs must derive from Cog

pseudo saffron
#

its there

golden portal
sick birch
#

Oh didn't see that

young dagger
golden portal
pseudo saffron
golden portal
pseudo saffron
#

oh

#

thank you

golden portal
#

welcome

slate swan
#

well i haven’t made anything yet im jus looking for someone to help me get it

sick birch
young dagger
# golden portal do it in a global error handler

Would this do the work?

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send("This command can only be used in a server, not in direct messages.")```
tough lance
#

also do an else statement for other errors

golden portal
golden portal
young dagger
golden portal
young dagger
# golden portal `commands.NoPrivateMessage`

So this is what I'm looking for:

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send(str(error))
    else:
        # Handle other errors here
        raise error```
golden portal
white citrus
#
            ccog = interaction.client.get_cog(module)
            
            
            if ccog is not None:
                #Page of a choosen cog
                
                emoji = getattr(ccog, "COG_EMOJI", None)
                
                embed = nextcord.Embed(title=f"{emoji} __{ccog.qualified_name}__" if emoji else f'_{ccog.qualified_name}_',
                                       description=f"{ccog.description or '...'}",
                                       colour=config.blurple)
                
                
                for cmd in ccog.application_commands:
                    embed.add_field(name=cmd.get_mention(),
                                    value=f'{cmd.description or "..."}\n\uFEFF')
                    if cmd.children:
                        for sub in cmd.children:
                            embed.add_field(name=sub.get_mention(),
                                        value=f'{sub.description or "..."}\n\uFEFF')
                    else:
                        pass
                await interaction.edit_original_message(embed=embed)```
#

it does not find the subcommands

pseudo saffron
#

why i cant make requests in discord py ?

pallid meadow
#

are you getting any error?

white citrus
pallid meadow
#

Anxie

#

I’m on mobile rn so it’s kinda hard to read the code my apologies

pseudo saffron
pseudo saffron
pallid meadow
#

Can you show the error

pseudo saffron
#

2023-02-02 19:45:22 ERROR discord.ext.commands.bot Ignoring exception in command None

pallid meadow
#

Can you show the code

pseudo saffron
#

yes this is the error i get

#

when i try to use requests or even insert a image to an embed

pallid meadow
#

Can you show the code though?

pseudo saffron
#

2023-02-02 19:45:22 ERROR discord.ext.commands.bot Ignoring exception in command None

#
    @commands.command
    async def boxen(self,ctx,member:discord.Member):
        embed=discord.Embed(colour=0x40E0D0,title=f'{ctx.message.author.name} schlägt {member.name}')
        embed.set_image('https://media.tenor.com/Lho_KrumiL4AAAAM/kevin-hasbu.gif')
        await ctx.send(embed=embed)```
slate swan
#

@commands.command()

pseudo saffron
#

oh

white citrus
young dagger
slate swan
#

!d discord.ext.commands.CommandNotFound ignore this exception in yr error handler

unkempt canyonBOT
#

exception discord.ext.commands.CommandNotFound(message=None, *args)```
Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
young dagger
slate swan
#

yes

wraith meteor
#

hey gays, how it possible to reload VOSK module and model on runned program?
this wey
def reloadmodule(): importlib.reload(vosk)
ist work

slate swan
#

who could help with message intents

spice jewel
#

File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection transp, proto = await self._wrap_create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection raise ClientConnectorCertificateError(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:992)')]

#

any solutions?

spice jewel
sick birch
# spice jewel yes

Go into your "Applications" folder in Finder, find the "Python" folder, double click "Install Certificates" or whatever it's called

spice jewel
#

it keeps spamming that

#

I'll retry

sick birch
#

lemon_grimace That's about the extent of my knowledge on debugging on Mac

spice jewel
#

File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection raise last_exc File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection transp, proto = await self._wrap_create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/aiohttp/connector.py", line 982, in _wrap_create_connection raise ClientConnectorCertificateError(req.connection_key, exc) from exc aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:992)')]

#

still the same error, if anyone can help Im on mac

sick birch
#

Was this after you ran the install certificates file?

pliant gulch
#

& Have you tried rebooting your mac

spice jewel
pliant gulch
#

Like, you didn't accidentally install it on 3.10

sick birch
slate swan
slate swan
# slate swan so help me 💯

Many bots don't require message intents at all. If it's your bot then you should have a clear idea of which intents it needs, and why.

slate swan
#

Where's the documentation for buttons with discord.py?

#

So I was testing around with the fetch_invite() method and ran into an error of exceeding 6000 characters in an embed, but I shouldnt be getting that error. So I made a test command and it still gives me the error of exceeding the 6000 limit. Here is the test command:

@client.command(name='vanitytest')
async def vanitytest(ctx, *, url=None):
    await ctx.message.delete()
    user = ctx.author
    if user.id == ownerID:
        embed = discord.Embed(colour = discord.Colour.red(),)
        try:
            result = await client.fetch_invite(url)
            embed.add_field(name=url, value='Valid', inline=False)
        except discord.NotFound:
            embed.add_field(name=url, value='Invalid', inline=False)
        return await ctx.send(embed=embed)
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed: Embed size exceeds maximum size of 6000
naive briar
unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
slate swan
#

what's the best way to set them up?

naive briar
#

Subclass the view object

slate swan
#

mehh

#

guys how do i make my bot update a message everyday? Like maybe an embed with the date in a separate locked channel that i wanna update like a calendar everyday?

#

How do you check if the button was pressed?

naive briar
#

The callback

slate swan
slate swan
naive briar
#

!d discord.ui.Button.callback

unkempt canyonBOT
#

await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The callback associated with this UI item.

This can be overridden by subclasses.
slate swan
#

wheres te examples again

naive briar
#

Try to look for yourself for once

slate swan
#

sorry Idk how to use google

slate swan
#
cannot import name 'InvalidArgument' from 'discord'```
slate swan
tired pollen
#

See examples on github how you can create slash commands

tired pollen
cloud dawn
tired pollen
#

Its outdated right now you need to use app_commands

cloud dawn
waxen willow
#

who knows jadi mirmirani?

cloud dawn
unkempt canyonBOT
waxen willow
#

how can i make a function to show phi algorithm in terminal

#

with pyton

maiden sonnet
#

I created an economy bot with mongodb but for the bot verification i need my users to be able to get their data deleted. I just cant figure out how i could do this.. Can anyone help me?

naive briar
#

Who would have thought

cloud dawn
#

Also pretty sure economy bots either don't delete it or delete it on guild leave event.

cloud dawn
#

A cross guild economics bot could also delete if it is in no guild that uses the bot.

maiden sonnet
maiden sonnet
#

Im not that good at coding so i just dont know how i could create a command that wipes the entire id and inventory

cloud dawn
#

Looked at docs, MongoDB confuses me, maybe someone at #databases knows?

maiden sonnet
#

ill try that

#

ty for trying to help tho

#

have a nice day 👍

gusty flax
#

nvm

slate swan
#

can someone help

#

i keep getting this

#

prediction_grid[int(prediction[count])] = ':good:'

#

Traceback (most recent call last):
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 130, in auth_mines
prediction_grid[int(prediction[count])] = ':good:'
ValueError: invalid literal for int() with base 10: ' '

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Auth/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'paid_pattern_mines' raised an exception: ValueError: invalid literal for int() with base 10: ' '

#

full trace back

#

@shrewd fjord

#

!e int(" ")

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: ' '
slate swan
#

" " is not an integer

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

so im trying to do that if someone sets a role with database so it will save it and everytime they will run a specific command i made itll mention the role, how do i start does anyone have tutorial or example

tough lance
#

Tias

slate swan
shrewd fjord
#

Yes

slate swan
#

and then when they run like !h so its pinging the role

shrewd fjord
#

!set_role mention

#

!h

slate swan
#

yes

shrewd fjord
#

I see

#

Pretty easy,
!set_role @lofty plovertion_the_role

slate swan
#

oh

shrewd fjord
#

Then in the database there should be 2 column

#

role_id and guild_id

slate swan
slate swan
shrewd fjord
#

Yes cool

slate swan
#

await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")

shrewd fjord
#

Yes too good

#

Now do is on set_role command try doing this
await cursor.execute(f"SELECT role_id FROM guild WHERE guild = {ctx.guild.id}")
data=await cursor.fethone()
if data is None:
#here u r going to insert values

#

then
#if it doesnt return None
else:
#update the role id on the database

#

Commit the changes and close connection as well as db

slate swan
#

oh i did that

shrewd fjord
#

Then u r almost done..

shrewd fjord
#

Your code is fine

slate swan
#

oh

slate swan
shrewd fjord
#

Thing is u need to close the database and connection too..

slate swan
#

oh

shrewd fjord
#
 else:
    await ....
 await cursor.close()
await db.commit()
await db.close()```
slate swan
#

fdid that

shrewd fjord
#

the else should be above cursor.close()

slate swan
shrewd fjord
#

What is !h then?

naive briar
#

They both automatically closed after the context manager block ends

slate swan
shrewd fjord
#

I forgor, f, i am actually used to sqlite3 not aiosqlite aand idk what's my problem to use asynchronous lib 💀

shrewd fjord
#
if data:
                await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (ctx.guild.get_role, ctx.guild.id,))
            else:
                await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (ctx.guild.get_role, ctx.guild.id,))```
#

Why this thing exist on !h then?

naive briar
shrewd fjord
slate swan
#

idk tbh

shrewd fjord
#

On !h
you should be fetching the datas not changing them

#

so if data:
#means the role_id exists...

#

so just do this

slate swan
#

oh right!

#

I need someone to help me solve one command.

In return, I can pay because I can't stand it mentally anymore. If anyone wants more details send me a dm.

naive briar
#

Just ask your questions

shrewd fjord
#

Then use get_role method

naive briar
#

No need to pay or anything yert

shrewd fjord
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
slate swan
#

tysmmm

shrewd fjord
shrewd fjord
# slate swan tysmmm

So u can now get the role role obj easily with this method and just now use role.mention to ping it or whatever

#

Also if data returns None then tell them to do set_staff first and set a role

#

Kinda ez imo

slate swan
#

is that good?

    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,))
            role_id = await cursor.fetchone()
            if role_id:
                if not role_id[0] == 1:
                    return```
naive briar
#

Why are you selecting twice

slate swan
shrewd apex
#

whats == 1 for?

slate swan
#
 if data:
          em = nextcord.Embed(title="Leveling LeaderBoard", color=0x88e86f)
          count = 0
          for table in data:
              count += 1
              user = ctx.guild.get_member(table[2])
              em.add_field(name=f"{count}. {ctx.author.name}#{ctx.author.discriminator}", value=f"Level - **{table[0]}** | XP - **{table[1]}**", inline=False)
          return await ctx.send(embed=em)
    return await ctx.send("There Are No Users In The LeaderBoard 😢 ")``` smt like that now? did that in my old code-
shrewd fjord
#

No 💀

shrewd fjord
#

Just
if role_id:
role=ctx.guild.get_role(role_id[0])

#

This is how u get the obj

slate swan
#

oh not if role_id:
if not role_id[0] == 1:?

shrewd fjord
#

Nope

#

Wait 🗿

#

@shrewd apex or @naive briar

#

Is it going to return list?

#

Or directly going to return the jd

#

Id*, i kinda forgot

naive briar
#

Tuple

shrewd fjord
#

Oh yeah

shrewd apex
#

its indexable so dosent matter lol

shrewd fjord
shrewd apex
#

unpack it or make a dataclass

shrewd fjord
#

Ye 🗿

#

Asher Peepo_UwU

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

until now

shrewd fjord
slate swan
#

oh yeah

#

do i have to add more stuff or i finished?

shrewd fjord
#

U r basically dine

#

Done*, except idk still where are you going to use the role obj

slate swan
#

maybe ill change it later

#

oop- it shows an error

#
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 402, in <module>
    async def invite(interaction: nextcord.Interaction):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1399, in decorator
    result = command(name=name, cls=cls, *args, **kwargs)(func)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1660, in decorator
    return cls(func, name=name, **attrs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 316, in __init__
    raise TypeError("Callback must be a coroutine.")
TypeError: Callback must be a coroutine.```
shrewd fjord
#

Check line 402

#

Give a ss ig

slate swan
#

oh

#

line 402 async def invite(interaction: nextcord.Interaction):

shrewd fjord
#

The ss please 🗿

slate swan
#

Oh ok

shrewd fjord
#

Nothing is wrong pithink

#

@naive briar ...

#

Callback must be coroutine 🗿

naive briar
#

I wonder why

shrewd fjord
slate swan
shrewd fjord
#

...

#

Can you give your import list ss?

slate swan
#

yes

#

WAIT

#

fixed it lol

#

nooo now when i run the set staff command it shows that

naive briar
#

Code

slate swan
#
@bot.command()
async def set_staff(ctx):
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,))
            data = await cursor.fetchone()
            if data:
                await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (ctx.guild.get_role, ctx.guild.id,))
            else:
                await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (ctx.guild.get_role, ctx.guild.id,))
        await cursor.close()
        await db.commit()
        await db.close()



class MyButton(nextcord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.value = None
    
    @nextcord.ui.button(emoji=":NoaOkay:", label="Claim", style=nextcord.ButtonStyle.green,custom_id="myButton")
    async def my_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
        if interaction.permissions.manage_messages == False:
          return await interaction.response.send_message(content="**Only staff can claim this helpme!**", ephemeral=True)
        button.disabled = True 
        button.label = f"Claimed by - {interaction.user.name}#{interaction.user.discriminator}" 
        await interaction.response.edit_message(view=self)



@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
       embed = nextcord.Embed(title="Error ![NoaX](https://cdn.discordapp.com/emojis/1070771504301740152.webp?size=128 "NoaX")", description='** ![NoaX](https://cdn.discordapp.com/emojis/1070771504301740152.webp?size=128 "NoaX") You have cooldown, please try again in `{:.2f}` seconds!**'.format(error.retry_after))
       await ctx.send(embed=embed, delete_after=4)
    else:
        raise error


@bot.command(aliases=["H", "helpme", "Helpme"])
@commands.cooldown(1,60,commands.BucketType.user)
async def h(ctx, *,message='No reason provided ![NoaX](https://cdn.discordapp.com/emojis/1070771504301740152.webp?size=128 "NoaX")'):
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,))
            role_id = await cursor.fetchone()
            if role_id:
                role = ctx.guild.get_role(role_id[0])
    check = ctx.author.voice
    if check is None:
      voice = f'Not in a VoiceChannel ![NoaX](https://cdn.discordapp.com/emojis/1070771504301740152.webp?size=128 "NoaX")'
    else:
      voice = ctx.author.voice.channel.mention
    emeb12233 = nextcord.Embed(description=f'{ctx.author.mention} - Needs your help ! ![NoaBell](https://cdn.discordapp.com/emojis/1070772152665649202.webp?size=128 "NoaBell") ',color=0x6c97c5)
    emeb12233.add_field(name="__**Reason:**__", value=f'{message}', inline = False)
    emeb12233.add_field(name="__**Room:**__", value=voice, inline = False)
    emeb12233.add_field(name="__**User:**__", value=ctx.author.mention, inline = False)

    emeb12233.set_footer(icon_url=ctx.author.avatar, text=ctx.author.name + "#" + ctx.author.discriminator,)
    emeb12233.set_thumbnail(url=ctx.author.avatar)
    await ctx.send("<@&" + role + ">", embed=emeb12233, view=MyButton())

@bot.command()
async def uytsgad7ygs9ahyd7sa67tfdsayhduasyuhdjsa6sya(ctx):
    view = MyButton()
    await ctx.send(view=view)```
naive briar
#

Why are you passing get_role meth as a value

slate swan
#

uh

#

its for getting the role id

shrewd fjord
#

Yeah i wonder too, like why u did so much work xd

slate swan
shrewd fjord
slate swan
#

also an option yes

naive briar
#

Or just role.mention 🐈

slate swan
#

changed it

#

but i dont get it like whys the error

#

oh wait got it

slate swan
#

ctx.guild.get_role bc of that right

shrewd fjord
#

...

slate swan
#

what do i do instead just ctx.get_role

shrewd fjord
#

No?

slate swan
#

oh then

shrewd fjord
#

ctx.guild.get_role to be exact

#

One bad thing can happen is, if the role doesnt exist get_role will return None

#

Make sure to handle it :)

#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
slate swan
#

like !set_staff @hadsysysds

shrewd fjord
#

So yeah

slate swan
#

ohh

#
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 60, in set_staff
    await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (ctx.guild.get_role, ctx.guild.id,))
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 512, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 491, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1381, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 948, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 174, in wrapped
    raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.``` full error
shrewd fjord
#

Wait wait td

#

Bro 🗿

#

async def set_staff(ctx, role: discord.Role)

slate swan
#

WAIT

#

how did i

#

omg

shrewd fjord
#

🗿💀

slate swan
#

yesyes tysmsmsmms

shrewd fjord
#

If any error i am here to get ur back or catglal xd

slate swan
#

AttributeError: 'NoneType' object has no attribute 'id'

upbeat otter
wintry canyon
#

so i have a question

#

im trying to make a command

#

which can trigger midjournes command /imagine prompt

#

it sends out the message yeah, but it doesnt trigger midjourneys command

#
if message.content.startswith("$Midjourney"):
            midjourneyPrompt = " ".join(message.content.split()[1:])
            print(f"midjourneyPrompt: {midjourneyPrompt}")
            original_channel = message.channel
            target_channel_id = 1071107593692528660
            target_channel = bot.get_channel(target_channel_id)
            await target_channel.send(f"/imagine {midjourneyPrompt}")
            target_channel_response = await bot.wait_for('message', check=lambda m: m.channel == target_channel and m.attachments)
            image_url = target_channel_response.attachments[0].url
            midjourney_response = requests.get(image_url)
            await original_channel.send(file=discord.File(io.BytesIO(midjourney_response.content), "midjourney.png"))
            time.sleep(2)
            os.remove("midjourney.png")
slate swan
upbeat otter
upbeat otter
slate swan
upbeat otter
upbeat otter
slate swan
#

i dont rlly understand ur question

wintry canyon
upbeat otter
wintry canyon
#

yessir

upbeat otter
slate swan
# upbeat otter from where are you getting the `role` variable for `role.id`

oh, py @bot.command() async def set_staff(ctx, role: nextcord.Role): async with aiosqlite.connect("main.db") as db: async with db.cursor() as cursor: await cursor.execute('SELECT role_id FROM role WHERE guild = ?', (ctx.guild.id,)) role = await cursor.fetchone() if role: await cursor.execute('UPDATE role SET role_id = ? WHERE guild = ?', (role.id, ctx.guild.id,)) else: await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', (role.id, ctx.guild.id,)) await ctx.send(f"Successfuly set the helpme staff role to - {role.mention}") await db.commit()

#

there the role

upbeat otter
#

like where you get journeyWhatever variable

wintry canyon
#

ye

#

so when i write /imagine press space then appears like a prompt box

#

for some reason the script cannot trigger that

upbeat otter
upbeat otter
#

idk how slash commands can be invoked 💀

#

sorry

slate swan
#

ty ill try now

#

like

#

do i change it or what

upbeat otter
#

name, the var name

slate swan
#

okay

#

async def set_staff(ctx, role_: nextcord.Role):
like that

upbeat otter
#

hm, you could do that

slate swan
#

what do i do next then

#

SHAHDASHDYAG

#

TYSM TYSM EVERYONE THE HELPED AAHHAHAHHAH

young dagger
young dagger
slate swan
#

Its an option there you can look at a tut

young dagger
#

Thanks hattip

waxen granite
#

How to do auto update the stuff after someone updates the bot for their server?

somber imp
#

hey guys! i use an orm for postgres db. any how can i add a column to a table without needing those migration versions? its a one time thing

normal reef
#

how do you accept file from user

slate swan
#

So I was testing around with the fetch_invite() method and ran into an error of exceeding 6000 characters in an embed, but I shouldnt be getting that error. So I made a test command and it still gives me the error of exceeding the 6000 limit. Here is the test command:

@client.command(name='vanitytest')
async def vanitytest(ctx, *, url=None):
    await ctx.message.delete()
    user = ctx.author
    if user.id == ownerID:
        embed = discord.Embed(colour = discord.Colour.red(),)
        try:
            result = await client.fetch_invite(url)
            embed.add_field(name=url, value='Valid', inline=False)
        except discord.NotFound:
            embed.add_field(name=url, value='Invalid', inline=False)
        return await ctx.send(embed=embed)
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed: Embed size exceeds maximum size of 6000
naive umbra
slate swan
#

thats where we're at currently...

naive umbra
#

so you get an embed error despite there not being an embed sent here?

slate swan
#

exactly 💀

naive umbra
#

do you have an on_message listener?

slate swan
naive umbra
#

nothing more to it?

slate swan
#

nope

naive umbra
slate swan
slate swan
# slate swan

the error is coming from somewhere else where you tried to send an embed
Most probably because you have some event or task that does it

#

!paste send your full code

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
naive umbra
#
    embed = discord.Embed(
        colour = discord.Colour.red(),
        title = f"Bot Error Found",
        description = "User: {} | Error: {}".format(ctx.message.author.name, error)
    )
```this could be the problem
#

errors can be quite long lol

#

especially dpy's

slate swan
slate swan
#

but yeah that seems like the part where error comes from

naive umbra
# slate swan

now that i see the full traceback, i can assure you that the embed i sent above is the problem

slate swan
#

what can I do as an alternative?

#

just use print?

#

i use a log file

naive umbra
slate swan
#

or you can send the error in two seperate messages

#
@client.event
async def on_command_error(ctx, error):
    channel = client.get_channel(1056704831051542653)
    if isinstance(error, CommandNotFound):
        print(error)
        return
    if isinstance(error, commands.BadArgument):
        print(error)
        return
    if isinstance(error, commands.MissingRequiredArgument):
        print(error)
        return
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.message.delete()
        embed = discord.Embed(colour = random.choice(colors),title = "**ERROR: Cooldown Active!**",description = (f'You Are On Cooldown! You Can Use This Command In: {round(error.retry_after, 2)} seconds.'))
        msg = await ctx.send(embed=embed)
        await asyncio.sleep(6)
        return await msg.delete()
    if isinstance(error, CheckFailure): 
        print(error)
        return
    embed = discord.Embed(colour = discord.Colour.red(),title = f"Bot Error Found",description = "User: {} | Error: {}".format(ctx.message.author.name, error))
    embed.set_footer(text="XIN Networks")
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/788698131898171424/788702201832669194/XIN_GIF_3.1.gif')
    return await channel.send(embed=embed)

mind giving me an example of that? @slate swan

slate swan
#

before you tried to handle the exception

#

you might not need to do this if youre able to fix the main issue

#

💀 wall of text

#

you're ratelimited for that endpoint

nocturne charm
#

Hello! I hope this message finds you well. I wanted to share with you a project that I've been working on. I recently created a Discord bot that I think could be a valuable addition to your server. It's designed to enhance the overall Discord experience with a range of helpful features. I would love for you to check it out and let me know what you think. If you're interested, you can find more information and add the bot to your server by visiting its GitHub repository. Thank you for your time, and I hope you enjoy the bot!
here is the github: https://github.com/LuciHusband/Outro-Bot 😄

GitHub

A goofy Discord bot that plays an epic outro song for a specified user! - GitHub - LuciHusband/Outro-Bot: A goofy Discord bot that plays an epic outro song for a specified user!

slate swan
slate swan
slate swan
#

lol then respect the ratlimits 🙏

slate swan
lethal surge
#

got a error with webhooks

#
postData = {
            "embeds":[
                {
                    "title":"Escanor Stock Scraper",
                    "description":time,
                     "fields":[
                        {
                            "name":"Stock Link",
                            "value":f'https://finance.yahoo.com/quote/{stock.ticker}'
                        },
                        {
                            "name":"Stock Price",
                            "value":stock.price
                        },
                        {
                            "name":"Stock Fair Price",
                            "value":stock.fairPrice
                        },
                        {
                            "name":"Stock EPS",
                            "value":stock.eps
                        },
                        {
                            "name":"Stock Cashflow",
                            "value":stock.freeCashFlow
                        },
                        {
                            "name":"Stock PriceToIntrinsic Margin",
                            "value":marginOfFairness
                        }
                    ]
                }
            ]
        }


        postData = json.dumps(postData)
#

error code 400

#

with formatting

slate swan
#

Get better

slate swan
#

Hey I have a question. Would you be able to make a discord bot that gives users a role that allows them to access all channel after typing in a 5 digit code which I can generate.
However, they will lose their rank ever 24 hours, forcing them to type in the same code in order to regain access to the server.
I would also like to have the ability to change the code whenever I'd like.

Thanks.

plucky shoal
#

Though not sure about the 24 hour timer for every user in case you shutdown the bot for any reason

#

You have something so far?

slate swan
#

im a newbie

#

i tried java, didnt work

plucky shoal
#

Well that's something pretty advanced for a newbie

#

Maybe you should try to make a simpler function bot to get familiar

#

It'll help to avoid lots of mistakes later

slate swan
#

How do I check if the person who pressed a button is the same as the person who invoked the command?

naive briar
#

Store the user object in the class and check it

slate swan
naive briar
#

Same thing

slate swan
#

How do you allow multiple button presses? Like for example, non author presses button it allows the button to still be pressed

flat pier
#

this should be the default behavior unless you manually disable the button when its clicked

slate swan
#

oh yeah I forgot I added self.stop() lol

torn sail
#

does anyone happen to know the color of an embed background in light theme?

torn sail
smoky sinew
#

i'll figure it out right now

torn sail
#

oh thanks, how do you do it

smoky sinew
#

#FFFFFF

torn sail
#

nah its not that lol

smoky sinew
#

yes it is

slate swan
#

How can I only allow a command to be ran by the server owner? The deco only works for bot owner iirc

smoky sinew
smoky sinew
torn sail
#

thanks for telling me color picker tho

#

its 0xF2F3F5

pulsar bridge
#

Does member.flags still work?
It's throwing me a Member object has no attribute 'flags' error, but the docs say that it's an existing Attribute

vocal snow
naive briar
#

What docs are you looking at

vocal snow
pulsar bridge
pulsar bridge
naive briar
#

Just sort it

pulsar bridge
#

huh?

vocal snow
pulsar bridge
#

right

naive briar
#

!d discord.PublicUserFlags

unkempt canyonBOT
pulsar bridge
# unkempt canyon

There's a difference between the Public user flags, and the member specific flags, isn't there?
Public is for things like badges.
Member specific flags can tell you if the user has left and rejoined the server before. Which was what I'm trying to find.

slate swan
#

Can you access a users date of birth without making your own database and asking for user input? Since discord requires it to make an account.

naive briar
#

No

slate swan
#

Rip 😢

clear elm
#

i'm trying to make it so when someone uses /suggestion and the suggestion sends, a thread will be made by the bot on the message. i've almost got it, it currently does everything above except for make the thread on the suggestion. it creates it in the channel. here's my code

@bot.tree.command(name="suggestion", description="Sends a suggestion to our suggestion channel!")
async def _suggestion(interaction, suggestion:str):
    channel = bot.get_channel(1059976520376012811)
    suggestEmbed = discord.Embed(color=0xFF5349)
    suggestEmbed.set_author(name=f'New suggestion by {interaction.user}', icon_url = f'{interaction.user.avatar}')
    suggestEmbed.add_field(name='The suggestion is:', value=f'{suggestion}')

    message = await channel.send(embed=suggestEmbed)
  
    await message.add_reaction('✅')
    await message.add_reaction('❌')

    channel = bot.get_channel(int(1059976520376012811))
    thread = await channel.create_thread(
    name=f"{suggestion} Discussion",
    reason="Suggestion",
    type=discord.ChannelType.public_thread)

    embed=discord.Embed(title=f"Discuss {interaction.user}'s suggestion!", color=0xFF5349)
    embed.add_field(name="Like, dislike or want to add onto someones suggestion?", value="Do that here! In this thread, you can discuss what you like, dislike or something smiliar you'd like to see!", inline=False)
    embed.set_author(name = f'{interaction.user}', icon_url = interaction.user.avatar)
  
    await thread.send(embed=embed)
  
    embed=discord.Embed(title="Successful!", color=0x23B425)
    embed.add_field(name="This command was successful.", value="Your suggestion was successfully posted in [#1059976520376012811](/guild/267624335836053506/channel/1059976520376012811/)", inline=False)

    await interaction.response.send_message(embed=embed)```

i run the command, everything works but as you can see it makes the thread in the channel rather the on the message
slate swan
#

!d discord.Message.create_thread

unkempt canyonBOT
#

await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a public thread from this message.

You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.

The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel").

New in version 2.0.
slate swan
#

How do you set channel permissions? I thought it's just channel.set_permissions(role, perms)

clear elm
slate swan
#

no.

#

you're using the wrong method

#
thread = await channel.create_thread(
``` means create a thread in channel ...
#

you should be using ```py
message.create_thread(

clear elm
#

ok thanks

slate swan
#

where's the list of the permission names?

#

!d discord.Permissions

unkempt canyonBOT
#

class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update "discord.Permissions.update").
slate swan
#

check the attrs of this class, those are perm names

slate swan
#

yep

clear elm
#

so it'd be?

    channel = bot.get_channel(int(1059976520376012811))
    thread = await message.create_thread(
    name=f"{suggestion} Discussion",
    reason="Suggestion",
    type=discord.Message.public_thread)```
#

or would it still be

    type=discord.ChannelType.public_thread)```
#

oh i dot need type

#

thank you so mucch, i spent so long on that and couldn't figure it out lol

slate swan
#

@slate swan How do you get the everyone role object

slate swan
unkempt canyonBOT
slate swan
#

or Guild.get_role(Guild.id)

clear elm
#
  File "main.py", line 96, in <module>
    async def _kick(interaction, member: discord.Member, *, reason='None'):
  File "/home/runner/kas/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
    command = Command(
  File "/home/runner/kas/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/home/runner/kas/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
    raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'reason' is missing a type annotation in callback '_kick'```
slate swan
#

you need to typehint every param in a slash command

clear elm
#

what does that mean- 😭 i only started making slash commands recently, i used to just make normal commands

slate swan
clear elm
#

ohh ok

slate swan
#

you might have done something like ```py
async def command(ctx, member: discord.Member)

#

it's the same thing

clear elm
#

ok

#

how would i do it with a reason

#

would it be like

reason:str```
clear elm
#

@slate swan sometimes the /suggestion commands works and sometimes it doesnt, when it doesnt, i keep getting this error

  File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 83, in _suggestion
    thread = await message.create_thread(
  File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/message.py", line 1207, in create_thread
    data = await self._state.http.start_thread_with_message(
  File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Must be 100 or fewer in length.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/kazue/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'suggestion' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Must be 100 or fewer in length.```
slate swan
#

What's the permission name to timeout members

#

moderate_members?

naive briar
#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
naive briar
#

Read the docs

naive briar
#

Read the error, threads' names cannot be more than 100 characters

clear elm
#

ohhh ok

gloomy bramble
#

guys can somebody just give me a basic boilerplate for bot?

#

i just need sample code with the imports and the token line and just one / command that replies with "hello"

vocal snow
#

which library?

gloomy bramble
#

nextcord or pycord is popular at the moment right?

clear elm
#
@bot.tree.command(name="help", description="Provides you with the help embed!")
async def _help(interaction):
    embed=discord.Embed(title="Help Menu", description="To find the help you're looking for, look below in this embed for whatever you need help with!", color=0xFF5349)
    embed.add_field(name="**__General Commands__**", value="Everyone can use these commands, abusing them will result in punishment.", inline=False)
    embed.add_field(name="``/help``", value="Provides you with this embed.", inline=False)
    embed.add_field(name="``/suggest``", value="Sends a suggestion to [#1059976520376012811](/guild/267624335836053506/channel/1059976520376012811/).", inline=False)
    embed.add_field(name="**__Moderation Commands__**", value="Staff with the correct permissions can use these commands. The following commands will be logged.", inline=False)
    embed.add_field(name="``k!purge``", value="Purges the specified amount of messages.", inline=False)
    embed.add_field(name="``k!kick``", value="Kicks the specified user with the reason.", inline=False)
    embed.add_field(name="``k!ban``", value="Bans the specified user with the reason.", inline=False)
    embed.add_field(name="``k!unban``", value="Unbans the specified user with the reason.", inline=False)
    embed.add_field(name="``k!mute``", value="Mutes the specified user with the reason and amount of time.", inline=False)
    embed.add_field(name="``k!unumte``", value="Unmutes the specified user with the reason.", inline=False)
    embed.set_author(name = f'{interaction.user}', icon_url = interaction.user.avatar)

    await interaction.response.send_message(embed=embed)```
was wondering if anyone could help me make those page buttons or even select menus like at the bottom of the carl bot help message. i've tried like literally everything, no clue how it works
gloomy bramble
#

whatever works best really

gloomy bramble
#

thanks king

gloomy bramble
#

oh wait it resumed

clear elm
shrewd fjord
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by editing the original message of a component or modal interaction.
gloomy bramble
#
import discord
import random

intents = discord.Intents.all()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=Your_guild_ID_here))
    print("ready")

@tree.command(name="truth", description="Selects a truth from the td.txt file.")
async def truth(int: discord.Interaction):
    with open("td.txt", "r") as f:
        truth_dare_lines = f.readlines()
        truth_lines = [line for line in truth_dare_lines if line.startswith("truth:")]
        selected_truth = random.choice(truth_lines).strip()[7:]
        await int.response.send_message(f"Truth: {selected_truth}")

@tree.command(name="dare", description="Selects a dare from the td.txt file.")
async def dare(int: discord.Interaction):
    with open("td.txt", "r") as f:
        truth_dare_lines = f.readlines()
        dare_lines = [line for line in truth_dare_lines if line.startswith("dare:")]
        selected_dare = random.choice(dare_lines).strip()[5:]
        await int.response.send_message(f"Dare: {selected_dare}")

@tree.command(name="tod", description="Selects either a truth or a dare from the td.txt file.")
async def tod(int: discord.Interaction):
    with open("td.txt", "r") as f:
        truth_dare_lines = f.readlines()
        truth_lines = [line for line in truth_dare_lines if line.startswith("truth:")]
        dare_lines = [line for line in truth_dare_lines if line.startswith("dare:")]
        if random.choice([True, False]):
            selected_truth = random.choice(truth_lines).strip()[7:]
            await int.response.send_message(f"Truth: {selected_truth}")
        else:
            selected_dare = random.choice(dare_lines).strip()[5:]
            await int.response.send_message(f"Dare: {selected_dare}")

client.run("your_discord_bot_token_here")
#

Not working can someone tell why

#

Like slash command not appearing

vocal snow
#

are you sure you have a valid guild id?

gloomy bramble
#

is guild id and server id the same thing?

#

if so, then yes

vocal snow
#

yes

gloomy bramble
#

i have it written like this:
await tree.sync(guild=discord.Object(id=1035927785652359299))

vocal snow
#
synced = await tree.sync(guild=discord.Object(id=Your_guild_ID_here))
print(f"Synced {len(synced)} commands")
``` you might want to add a print like that to debug
vocal snow
#

define it, tree.sync returns the commands that were synced

clear elm
#
    ) 
    ^
SyntaxError: unmatched ')'```
code:
gloomy bramble
#

ah wait

gloomy bramble
gloomy bramble
vocal snow
#

tree.sync returns the commands

#

why do you have an empty await

gloomy bramble
#

hmm

gloomy bramble
#

oh wait ah. bro lemme fix.

#

"synced zero commands"

naive briar
clear elm
vocal snow
naive briar
#

No, it's unmatched, remove it

clear elm
#

ok

#
    components=
               ^
SyntaxError: invalid syntax```
naive briar
#

Read the error, and learn basic Python syntax

#

!e

blahblahblah = 
     [] # ??
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     blahblahblah = 
003 |                    ^
004 | SyntaxError: invalid syntax
gloomy bramble
#

wait no

naive briar
#

You're doing a lot of API requests with that thing

gloomy bramble
#

okay wait lemme fix

#

okay it worked

gloomy bramble
raw quail
#
import discord
import asyncio
import aiohttp
import time
from discord.ext.commands import Bot, has_permissions, MissingPermissions, Cog
from discord.ext import commands
from random import *


class Test(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @commands.command()
    async def cnbc(self, ctx):
        t = randint(180, 600)
        old_links = []
        with open("old_links.txt", "r", encoding="utf-8") as file:
            old_links = file.read().splitlines()
        
        while True:
            try:
                channel = bot.get_channel(text_channel)
                base_url = 'https://www.cnbc.com/world/'
                async with aiohttp.ClientSession() as sess:
                    async with sess.get(base_url, headers={'user-agent': 'Mozilla/5.0'}) as res:
                        text = await res.text()
                        soup = bs(text, 'lxml')

                        title = soup.find("div", attrs={"class":"LatestNews-container"}).a.text.strip()
                        link = soup.find("div", attrs={"class":"LatestNews-container"}).a['href']

                        if link not in old_links:
                            embed=discord.Embed(title=title, url=link)
                            embed.set_author(name="CNBC")
                            await channel.send(embed=embed)
                            old_links.append(link)
                            with open("old_links.txt", "w", encoding="utf-8") as file:
                                file.write("\n".join(old_links))
                        else:
                            pass      
            except Exception as e:
                await channel.send("❗ CNBC = An error please check ❗")

            await asyncio.sleep(t)

async def setup(bot):
    await bot.add_cog(Test(bot))

it worked as well before seperate files using cog and other commands are working well with cogs but only crawling is not working without any errors :((

vocal snow
#

what do you mean "not working", are you getting an error?

naive briar
#

You're creating new client sessions and fileio every loop

vocal snow
#

as in, is the except part triggering?

raw quail
#

nope there is no errors but when i write a command on discord, its nothing happen but other commands are working well

#

only crawling function is not working 😭

vocal snow
#

remove the try-except, it should give you some idea

raw quail
#

ohhh

vocal snow
#

and maybe add something in the else so you know if it's executing

raw quail
#

thank you so much! i will try. but it was working as well before using cog. :((

cunning pasture
#

Are slash or traditional commands better?

naive briar
#

Prefix commands are far better in terms of argument parsing

vale wing
#

In terms they support arglist, I wouldn't say there are any more advantages regarding argparsing

#

The main advantage of prefix commands is there can be unlimited amount of them unlike slash commands

#

I can't really think of anything else

true scroll
#

Hello,
Is there away to set permissions in a private channel?
For example like this:

for channel in ctx.guild.channels:
            await channel.set_permissions(muted, speak=False, send_messages=False, read_message_history=True, read_messages=True)
clear elm
shrewd fjord
clear elm
shrewd fjord
#

Not hard 🗿

#

Hewo exen Peepo_UwU

vale wing
#

Hello

shrewd fjord
#

What's up xd

vale wing
shrewd fjord
true scroll
vale wing
#

I'm already fine ty

shrewd fjord
vale wing
shrewd fjord
#

!d discord.TextChannel.set_permissions

unkempt canyonBOT
#

await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sets the channel specific permission overwrites for a target in the channel.

The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.

The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.

If the `overwrite` parameter is `None`, then the permission overwrites are deleted.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
shrewd fjord
#

Hm...

shrewd fjord
clear elm
#

ok

#
class Dropdown(discord.ui.Select):
    def __init__(self):

        options = [
            discord.SelectOption(label='General', description='Provides you with general commands and information about them.', emoji='1️⃣'),
            discord.SelectOption(label='Moderation', description='Provides you with moderation commands and information about them.', emoji='2️⃣'),
        ]
      
        super().__init__(placeholder='Choose what type of help you need below.', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):

        await interaction.response.edit_message(embed=...)

class DropdownView(discord.ui.View):
    def __init__(self):
        super().__init__()

        self.add_item(Dropdown())


class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('k!'), intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')


bot = Bot()

@bot.tree.command(name="help", description="Provides you with the help embed!")
async def _help(interaction):
    embed=discord.Embed(title="Help Menu", description="To find the help you're looking for, look below in this embed for whatever you need help with!", color=0xFF5349)

    view = DropdownView()
  
    await interaction.response.send_message(embed=embed, view=view)```
shrewd fjord
#

Ohh xdd

#

Add value...

#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
shrewd fjord
#

value=...

#

Add some value so you can compare

#

like if self.values[0]==1or2orn:
#do something

#

Integer

clear elm
#
  discord.SelectOption(label='General', value=..., description='Provides you with general commands and information about them.', emoji='1️⃣'),
  discord.SelectOption(label='Moderation', value=..., description='Provides you with moderation commands and information about them.', emoji='2️⃣'),```?
shrewd fjord
#

value=1
value=2

raw quail
shrewd fjord
#

For first select option use 1 or whatever for 2nd use 2 or whatever

#

Should be unique for each options

clear elm
#

ok

clear elm
#

what else do i need to do?

naive briar
#

Do you even know what you're doing

shrewd fjord
shrewd fjord
clear elm
#

where in the code do i put the embed

raw quail
# shrewd fjord What's the prob

I put all the Discord commands in one Python file(main.py) And i studied about cog today and seperated python files of discord by function to make them easier to manage. However, only the crawl file does not work. There are even no errors. and other commands are working well in cogs.

clear elm
#

it says interaction failed but i got no errors

clear elm
#

@shrewd fjord

heady verge
#
Traceback (most recent call last):
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 976, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "C:\Users\LOKESH\Desktop\Lokesh\Pycord\cogs\giveaway.py", line 132, in start
    msg = await channel.send(embed=embed, view=view)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\abc.py", line 1622, in send
    state.store_view(view, ret.id)
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\state.py", line 386, in store_view
    self._view_store.add_view(view, message_id)
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 582, in add_view
    view._start_listening_from_store(self)
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 425, in _start_listening_from_store
    self.__timeout_expiry = time.monotonic() + self.timeout
                            ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'float' and 'Giveaway'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command 
    await ctx.command.invoke(ctx)
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\LOKESH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: unsupported operand type(s) for +: 'float' and 'Giveaway'```
#

i cannot figure out where the error is

keen dust
#

hi I need some help to make an invite tracker for my bot

#

I'm trying to figure out who invited my bot to whatever server they invited it too

#

so far I was able to get the server name

#

but not the member who invited the bot

#
async def on_guild_join(guild):  
        channel = bot.get_channel(CHANNEL NAME)
        invite = await guild.invites()
        integrations = await guild.integrations()

                   
                
        message = f'Member {#member name} invited to server: **{guild.name}**'        
        await channel.send(message)
#

theres the code so far

#

I tried using integrations to get the name but it doesn't work

#

I tried using ctx to get the member name with ctx.guild.id but that doesn't work

naive briar
young dagger
#

Is there any easier way to do this?

    if len(queue) == 1:
        embed = discord.Embed(title='1 player is currently in the queue',
                              description=f'{member.mention} has been added to the queue.',
                              timestamp=datetime.datetime.now(), color=discord.Color.blue())
    else:
        embed = discord.Embed(title=f'{len(queue)} players are currently in the queue',
                              description=f'{member.mention} has been added to the queue.',
                              timestamp=datetime.datetime.now(), color=discord.Color.blue())```
naive briar
#

Do what

cloud dawn
#

Oh you mean the s

naive briar
#

That would add s if the queue len is 1

cloud dawn
#

I'd just use player(s)

#

lol

naive briar
#

!e ducky_sus

cats = [1]
print("Multiple") if len(cats) == 1 else print("Single")
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

Multiple
naive briar
#

Just do > at this point

cloud dawn
#

JUst got up `okay lol

#

heart

young dagger
proud apex
#

how can you use a dictionary from another file and get data from it?

cloud dawn
#

!e ```py
queue = ["player"]

print(f"{len(queue)} player{'s' if len(queue) > 1 else ''} is currently in the queue")

queue = ["player", "player"]

print(f"{len(queue)} player{'s are' if len(queue) > 1 else ' is'} currently in the queue")

unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 1 player is currently in the queue
002 | 2 players are currently in the queue
cloud dawn
#

?

young dagger
#
print(f"{len(queue)} player{'s are' if len(queue) > 1 else ' is'} currently in the queue")```
#

Nvm

silk fulcrum
#

wow, the code looks different

#

it's more colourful now

naive umbra
#

new codeblock colors came like a month or two ago

silk fulcrum
#

It's just that I never looked at it

#

I was really into competitive coding last like 4 months

#

so I didn't use codeblocks in discord

#

didnt need it

keen dust
keen dust
#

wait you mean

#

discords audit log?

cloud dawn
#

yep

keen dust
#

but how did they implement that in their bot?

cloud dawn
#

Wot

keen dust
#

its a feature which can be applied in bots

cloud dawn
#

Yes. If you code it.

keen dust
#

so...how do you get the name of the member who invited the bot to the server?

#

I got how to print the server name

#

its just the member now

naive briar
#

There's no such thing, not even audit logs

keen dust
#

by invite tracker

naive umbra
# keen dust

afaik there is no possible way of making your client sub to an event that gives you invite tracking data, iirc bots like invite tracker uses an algorithm to figure out who invited who by storing the user who created the invite and then check if the invite use count went up at the same time a user joined, but it's really inaccurate for larger servers with frequent joins

cloud dawn
unkempt canyonBOT
vale wing
#

You need to compare invite usages before and after the join

#

That's how it works

cloud dawn
#

And I'm guessing they cache every single invite and have some kind of schedule queue to avoid any minor bugs.

naive umbra
#

how do they figure out which invite a user joined with though

#

say in a busy server like this one

#

with frequent joins, simultaneous joins are possible

cloud dawn
unkempt canyonBOT
naive umbra
cloud dawn
#

The comparing the invite usages before and after the join is just to identify whom invited whom.

naive umbra
#

yeah, quite inaccurate

cloud dawn
#

Not if you cache every single invite and instead of running it true async have a async schedule que.

keen dust
#

or store it all in a database

naive umbra
keen dust
#

but that would be really memory consuming

cloud dawn
keen dust
#

ic

cloud dawn
#

I don't see the usage in it anyways.

#
p_message = message.lower() 'hello' = 'hello welcome whatsup'
``` Syntax is a bit off.
naive umbra
#
p_message = message.lower() 'hello' = 'hello welcome whatsup'
``` this is the problem, what are you trying to do?
#

no, what is that line supposed to do

#

still quite vague

#

that line alone, what are you trying to do with it

#

seems like you should remove the "hello" = "hello ..." part completely

cloud dawn
#

Have you coded a lot in Python before this? Or have any experience regarding Discord or chatbots?

#

Chatbots are made using models and by tokenizing certain strings inside a sentence.

#

Here's an example of how that would look like if you're processing it. json {"intents": [ { "tag": "greetings", "patterns": ["hello", "hey", "hi", "good day", "greetings", "what's up"], "responses": ["Hello!", "Hey!"] }] }

#

This was a real rough example.

#

You'd also need to have a trainer for the module and to execute it.

#

List is longer just copied it.

#

It's pretty tough to make especially in a bot.

#

I recommend making it separate first then combine it.

#
        @client.event
        async def on_message(message):
            if message.author.bot:
                return
#

There are some good videos on youtube for chatbots. I recommend not watching videos that are 1 year or older.

#

Then learn how to make discord bots as well then later combine the 2 in 1 program.

#

I recommend having the google filter on < 1 year

#

This tutorial video makes me wanna make my own and then do it properly.

slate swan
#

the worst part is that they don't mention about the stuff that has heen outdated in the title or description, its just post and forget lol

#

*heen = been

kind pike
#

i have a error guys

#

`import requests
import time
import telegram

Your Telegram bot's API key

API_KEY = '***********'

The chat ID of the Telegram user or group you want to send the price to

CHAT_ID = '********'

The URL for the CoinMarketCap API endpoint for Bitcoin

BTC_PRICE_API_URL = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC&convert=USD'

The header for the CoinMarketCap API request

HEADERS = {
'Accepts': 'application/json',
'X-CMC_Pro_API_Key': '****************',
}

Initialize the Telegram bot

bot = telegram.Bot(token=API_KEY)

Function to get the latest price of Bitcoin

def get_btc_price():
response = requests.get(BTC_PRICE_API_URL, headers=HEADERS)
data = response.json()
btc_price = data['data']['BTC']['quote']['USD']['price']
return btc_price

Function to send the latest price of Bitcoin to Telegram

def send_btc_price_to_telegram():
btc_price = get_btc_price()
message = f'The current price of Bitcoin (BTC) is ${btc_price:.2f}.'
await bot.send_message(chat_id=CHAT_ID, text=message)

Send the price of Bitcoin to Telegram every hour

while True:
send_btc_price_to_telegram()
time.sleep(5)
`

#

how can i fixe it pls

cloud dawn
shut elk
#

https://paste.pythondiscord.com/pixeqamebu

    await interaction.response.defer()
    try:
        tim = round(time.time())
        if "m" in timestamp:
            tim+=int(timestamp.lower().replace("minutes","").replace("minute","").replace("m",""))*60
        if "h" in timestamp:
            tim+=int(timestamp.lower().replace("hours","").replace("hour","").replace("h",""))*3600
        if "d" in timestamp:
            tim+=int(timestamp.lower().replace("days","").replace("day","").replace("d",""))*86400
        await interaction.followup.send(f"`<t:{tim}:R>`")
    except:
        await interaction.followup.send(f"Error, please try minutes, hours, or days. For example, `10h`.")

Idk why there is unknown interaction error for the line of defer above. There's nothing that is blocking the code that I can tell... There was nothing running other than this part, it is a slash command I implemented and that was the only command that was used at that moment.

#

ping if here, thx

naive umbra
shut elk
# naive umbra you're not making any response?

uh basically defer is a type of response, so in the line await interaction.**response**.defer(), it responds to the interaction. Then, the other followups are basically needed for after a deferred msg is done

young dagger
#

How can I use the images from local directory? This isn't working.

                        thumbnail_url = f'/images/ranked-emblem/{lowered_rank}.png'
                        embed.set_thumbnail(url=thumbnail_url)```
#

I want to use images from /images/ranked-emblem/

naive umbra
naive umbra
#

yeah, and you're not doing that

shut elk
#

what

#

so what am i supposed to do

#

if i do response send msg as a proper response, im pretty sure it will not work

naive umbra
#

replace followup.send with response.send_message?

shut elk
#

interaction can only be responded once and yes

naive umbra
#

it should be

#

trying wont hurt

#

worst case, we can just dig into it further down and find another solution, but try that first

shut elk
naive umbra
#

and what error did you get

shut elk
shut elk
# shut elk

as i said, defer responds to the interaction and yes, its preparing for another response but since it already is responded, the only thing that you can use is followup

#

this is afaik, I've tried this when I started discord bot stuff and it didnt work

shut elk
#

like what i mean by it has to be followup

naive umbra
#

yeah, in that case i must've confused it, apologies

shut elk
#

alr, unknown interaction can be caused by blocking i heard so idk what is causing this problem if theres nothing blocking its so weird

naive umbra
#

i see, can you post the full traceback using the followups instead?

shut elk
#

uh

#

alr 1 sec

young dagger
#

How can I use the images from local directory? This isn't working.

                        thumbnail_url = f'/images/ranked-emblem/{lowered_rank}.png'
                        embed.set_thumbnail(url=thumbnail_url)```
shut elk
#

it was caused when someone else used it, im not exactly sure what happened

#

nvm then, if i get it again ill come here and show the traceback

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb ('read binary') mode. Also, in this case, passing filename to it is not necessary.
Please note that filename must not contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

young dagger
#

@slate swan But it should only set thumbnail if not Unranked. Do you know how to fix this?

    # Add rank emblem to the Embed
    rank, *_ = tier_and_rank.partition(" ")
    lowered_rank = rank.lower()
    if lowered_rank and lowered_rank != 'unranked':
        thumbnail_url = f'https://raw.communitydragon.org/latest/plugins/rcp-fe-lol-shared-components/global/default/{lowered_rank}.png'
        embed.set_thumbnail(url=thumbnail_url)

    # Send the Embed object to the user
    await ctx.channel.send(embed=embed)```
#

As with this code it will not add thumbnail if Unranked.

slate swan
#

How do you guys host your bots?

#

Using uptimerobot or some other websites. Or something completely different like webservers.

What if I don't use repl for bot creation then how should I host it so that it becomes available 24*7

upbeat otter
young dagger
upbeat otter
#

you have to provide a bytes-like object (use open or preferably aiofiles.open)

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
young dagger
#

@upbeat otter I'm using this

#

!local-file

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb ('read binary') mode. Also, in this case, passing filename to it is not necessary.
Please note that filename must not contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

upbeat otter
#

oh

#

the docs say something else, my bad

#

but the docs need to be correct lmao
(nvm I didn't read the whole thing, my bad

vestal snow
#

guys when i run my discord bot it says logging using static token and gives a long list of errorsw then a runtime error

upbeat otter
young dagger
#

Could I use this?

await ctx.channel.send(file=file if lowered_rank != 'unranked' else None, embed=embed)```
vestal snow
upbeat otter
# vestal snow

Your code is trying to use intents which haven't been enabled in your app on the discord dev portal

#
  • go to discord developers (https://discord.dev)
  • Go to Applications and open the required app
  • Go to the Bot Section and scroll down
  • Enable the intents your bot requires and hit Save
  • Try to run your code again
slate swan
#

It's a free hosting service

#

Like heroku

upbeat otter
#

heroku isn't free anymore

#

and free hosting services aren't really that much reliable nor are they good in their own ways

upbeat otter
slate swan
#

Oh

#

This vedio talks about it : https://m.youtube.com/watch?v=kIvfYWP-nTk

► [NEW] Host Your Discord Bot 24/7 For FREE! - (NOT Heroku)

Ever since Heroku announced they are no longer going to support free services starting November, people who want free hosting already can find an alternative to host their discord bots all for free! in today's video I present you a new discord bot free hosting service with 24/7 uptime,...

▶ Play video
naive umbra
#

i mean, instead of using these bs "free" solutions, just pay for a proper vps

#

i pay $0.97 per month for mine and i host like 7-8 apps on it, five nines uptime and it's running ubuntu, you have so much more options and flexibility with a vps than that

slate swan
clear elm
slate swan
#

@sick birch How I can get a channel object searching by channel name within a task?

sick birch
sick birch
#

How about the guild

slate swan
#

discord.utils.get(bot.guild.channels, name="channel") but bot.guild.channels doesn't exist so I don't know how to get it lol

sick birch
#

Do you have the guild ID, name, or something else to identify it?

#

Ah, nevermind that

sick birch
#

Wait until the bot is ready before the loop starts

slate swan
#

my loop isn't in a cog

slate swan
#

@sick birch How are you supposed to use tasks? it seems like it's blocking my code for some reason

sick birch
#

What is your task doing?

slate swan
sick birch
#

And how are you telling it's blocking?

slate swan
#

I'm using .listen() for the function to delete messages and an on_ready event to start the task

#

What do you think about uptimerobot and replit. I will get a webserver once my bot is ready.

sick birch
naive umbra
slate swan
#

@sick birch How can I make an interactive setup type command? Like you run ,setup and it will prompt you for certain things then wait for you to reply etc

pseudo saffron
#

can someone explain how i can use buttons with bot.wait_for ?

winged coral
#

wait for an interaction

#

check it's the one you want

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
slate swan
#

im trying to make a xp bot with a cog but the cog itself doesnt work. if i run the code without the cog it works just fine. no errors or tracebacks

class XPCOG(commands.Cog):
    def __init__(self, bot):
    self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
    print("ready")

    @commands.Cog.listener()
    async def on_member_join(self, member):
        # code here

    @commands.Cog.listener()
    async def on_message(self, message):
        # code here
    @commands.Cog.listener()
    async def update_data(self, users, user):
        # code here
    
    @commands.Cog.listener()
    async def level_up(self, users, user, message):
        # code here

    @commands.command()
    async def level(self, ctx, member: discord.Member = None):
        # code here

i just started using cogs, so if i have a bad question sorry

naive briar
#

Did you add the cog

slate swan
#

yeah

pseudo saffron
#

i watched litterly 20 tutorials

#

and everyone makes it diffrent

slate swan
naive briar
#

Don't watch YouTube tutorials

slate swan
naive briar
#

Yes

pseudo saffron
#

and give them a function

naive briar
#

There's a bunch of example there

pseudo saffron
# sick birch <https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py> her...
class Counter(discord.ui.View):

    # Define the actual button
    # When pressed, this increments the number displayed until it hits 5.
    # When it hits 5, the counter button is disabled and it turns green.
    # note: The name of the function does not matter to the library
    @discord.ui.button(label='0', style=discord.ButtonStyle.red)
    async def count(self, interaction: discord.Interaction, button: discord.ui.Button):
        number = int(button.label) if button.label else 0
        if number + 1 >= 5:
            button.style = discord.ButtonStyle.green
            button.disabled = True
        button.label = str(number + 1)

        # Make sure to update the message with our updated selves
        await interaction.response.edit_message(view=self)


@bot.command()
async def counter(ctx: commands.Context):
    """Starts a counter for pressing."""
    await ctx.send('Press!', view=Counter())``` i copied it like this in my code and it says no interaction possible
#

its everytime says it when i try press a button

pseudo saffron
#

yes

pseudo saffron
clear elm
slate swan
pseudo saffron
#

discord.ext.commands.bot this

slate swan
unkempt canyonBOT
#

Hey @pseudo saffron!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

pseudo saffron
#

@slate swan

slate swan
pseudo saffron
#

do i need to have the active developer badge to use buttons ?

slate swan
pseudo saffron
#

what u mean

#

even if i dont load my cogs it dont work

slate swan
# pseudo saffron what u mean

im not skilled enough, but somewhere before the button your previous code is doing something that doesnt let your button run

#

if you make a different file and run it there with just the button it will work

pseudo saffron
#

i will try

#

so you mean in a cog ?

slate swan
#

i mean that your button would work if your previous code wasnt there

#

because your previous code is interfering

pseudo saffron
#

but how is it interfering i mean i dont use any vars in it that could or running tasks

slate swan
#

idk, somehow it is

pseudo saffron
#

1 sec i will try just run the code without any other code

slate swan
#

it will work like that

chilly dove
#

you should be loading your cogs in async_hook

pseudo saffron
#

whats async_hook ?

chilly dove
#

or setup_hook i mean

clear elm
chilly dove
#

subclass your bot and override setup_hook thats where you should load cogs

pseudo saffron
#

yo @slate swan it dont even work without any other codes

#

just with the bot commands

chilly dove
pseudo saffron
#

to test if my code is messy