#discord-bots

1 messages · Page 185 of 1

golden portal
#
  1. discord enforce slash when they made message content a privileged intents -> no content no command
  2. you cannot apply for message content w/ the reason of message command
  3. slash command has a different framework than dpy's text commands (slash is too limited)
  4. hybrid command exist now, making slash/text compatible, but text is limited by slash
young dagger
#

Is this the right way to do it?

@client.command(name = 'queue')
async def queue_command(ctx):
    # Check if the message was sent in the allowed channel
    if ctx.channel.id == 712074759453671494:
        # Check if the user is in the specified voice channel
        if ctx.author.voice is None or ctx.author.voice.channel.id != 712072729406472374:
            if ctx.author not in queue:  # Check if the user is not in the queue
                queue.append(ctx.author)
                await ctx.send(f'{ctx.author.mention} has been added to the queue.')
            else:  # The user is already in the queue
                await ctx.send(f'{ctx.author.mention} is already in the queue.')
        else: # The user is in the specified voice channel
            await ctx.send(f'{ctx.author.mention} is already in the voice channel and cannot be added to the queue.')
    else:  # The message was not sent in the allowed channel
        await ctx.send("This command can only be used in the [#712074759453671494](/guild/267624335836053506/channel/712074759453671494/) channel.")```
#

I'm not sure if I should use if ctx.author.voice is None or ctx.author.voice.channel.id != 712072729406472374: or something else?

austere prairie
young dagger
# austere prairie You should use guard clauses instead of nesting if statements: ```py async def q...

So you mean like this right,

@client.command(name = 'queue')
async def queue_command(ctx):
    if ctx.channel.id != 712074759453671494:
        await ctx.send("This command can only be used in the [#712074759453671494](/guild/267624335836053506/channel/712074759453671494/) channel.")
        return
    if ctx.author.voice and ctx.author.voice.channel.id == 712072729406472374:
        await ctx.send(f'{ctx.author.mention} is already in the voice channel and cannot be added to the queue.')
        return
    if ctx.author in queue:
        await ctx.send(f'{ctx.author.mention} is already in the queue.')
        return
    queue.append(ctx.author)
    await ctx.send(f'{ctx.author.mention} has been added to the queue.')```
austere prairie
#

Yes

young dagger
#

Is it better to convert duration seconds to minutes before inserting it into the database for a mute infraction, or to keep it in seconds and convert it for display purposes only?

coral ermine
#

seeing this error

upbeat otter
upbeat otter
upbeat otter
#

!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.

young dagger
upbeat otter
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
upbeat otter
#

you can convert your seconds to a timestamp easily

young dagger
#

How can I make it appear in minutes? Example, Duration: 30 minutes

upbeat otter
#

you can use the relative time format

#

style = r

#

I think that's what you're looking for

young dagger
#

It should display the actual duration for the infraction

upbeat otter
young dagger
#

It shouldn't be used as a timestamp

upbeat otter
#

or a timedelta

upbeat otter
#

well, then just convert the seconds to minutes and stuff yourself

young dagger
#

Is it a good way to insert the duration seconds as an integer?

#

Or should I keep it as a string?

still heron
#

how i can fix this

quick gust
#

shouldn't you be taking in another argument after ctx?

naive briar
#

Just get command you wanted to run as an argument

#

Way way way cleaner

#

And why are you even converting IDs to string to compare them

#

Sure

#

Don't want anything I see

quick gust
#

ive no clue honestly

naive briar
#

You're miss message content intent

#

Not any hard to spot

quick gust
#

oh yeah that exists

#

u need message content intent for the bot to see your message

naive briar
#

If your bot can't access message contents, it can't process commands

#

!d discord.Intents.message_content

unkempt canyonBOT
#

Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:

• The message was sent by the client

• The message was sent in direct messages

• The message mentions the client

This applies to the following events...

tough lance
#

Getting this error when using dynamic cooldown

Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/disnake/client.py", line 700, in _run_event
  await coro(*args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1361, in on_application_command
  await self.process_application_commands(interaction)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/interaction_bot_base.py", line 1353, in process_application_commands
  await app_command.invoke(interaction)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/slash_core.py", line 719, in invoke
  await self.prepare(inter)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 331, in prepare
  self._prepare_cooldowns(inter)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/base_core.py", line 315, in _prepare_cooldowns
  bucket = self._buckets.get_bucket(inter, current)  # type: ignore
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/cooldowns.py", line 227, in get_bucket
  self._verify_cache_integrity(current)
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/cooldowns.py", line 212, in _verify_cache_integrity
  dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
File "/usr/local/lib/python3.10/dist-packages/disnake/ext/commands/cooldowns.py", line 212, in <listcomp>
    dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
AttributeError: 'function' object has no attribute '_last'

My code:

    def drop_cool(msg):
        if msg.author.id == 756018524413100114:
            return None
        print(msg.author.id)
        return commands.cooldown(1, 600)

    @commands.slash_command(description="Drops card")
    @commands.dynamic_cooldown(drop_cool, commands.BucketType.user)
    async def drop(self, inter: discord.ApplicationCommandInteraction):
        ...
vocal snow
#

the dynamic_cooldown callable is supposed to return Optional[Cooldown]

#

im guessing you just forgot to capitalize the C

balmy bobcat
#

Hi, my discord bot doesnt show its slash commands anymore, it worked until now but now none of them works

tough lance
#

Thanks

steady berry
#

how can i make simple bot with slash command

#

can i use ctx

steady berry
#

like this async def askgpt(ctx, arg):

balmy bobcat
#

did you setup the intents in your code?

intents = discord.Intents.all()
client = commands.Bot(command_prefix="m?",description="Mascarpone", intents=intents)
``` for example
vocal snow
steady berry
balmy bobcat
vocal snow
#

what error are you getting?

vocal snow
hushed galleon
#

can you double check the discord.py version you have installed with pip list?

vocal snow
#

latest version is 2.1.0

hushed galleon
#

did you run pip install --upgrade discord.py?

#

are you definitely sure you had the --upgrade flag? i cant think of a reason why it wouldnt upgrade otherwise

#

besides pip referring to another virtual environment

#

i mean a python virtual environment, not the remote console you're using

#

what command are you using to run your bot on the server?

#

wait so if you run pip list --outdated it really wont show discord.py as needing an update?

split forge
#

discord.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.

#

how to open that?

hushed galleon
#

"opening" an error message?

split forge
hushed galleon
#

ah screw it does it work if you run pip install discord.py==2.1.0

split forge
#

discord.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.

hushed galleon
#

but what is "opening" an error message? do you mean how to fix the error message? or hide it?

split forge
#

fix

#

I just make a bot which user have premium it will work on dm or anywhere
@commands.has_any_role(role)

split forge
hushed galleon
#

NoPrivateMessage is raised by the @commands.guild_only() check (and other guild-related checks, i forgot those raise it too), so if you dont want to see it you should either remove the check, or make an on_command_error listener that doesnt print that message

sick birch
#

How would has any role work in DMs 🤔

split forge
#

💀

split forge
steady berry
split forge
#

if I use only works in dm everyone can use it

hushed galleon
split forge
steady berry
#

if i use client.tree.comand and guild what scopes should i use for oauth2

hushed galleon
hushed galleon
steady berry
#

ok

hushed galleon
#

@commands.has_any_role() will "work" in any guild, just not in DMs, hence why i pointed to a custom check

#

!d discord.ext.commands.check

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
slate swan
#

just use virtual environments, fixes most permissions and version related issues

#

!venv

unkempt canyonBOT
#
Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
tough lance
#

is discord api down or something?

hushed galleon
#

ah, your python version is too old

#

2.0 raised the required version to 3.8 as described in that message

#

uhh i mean discord.py 2.0 raised the required python version to 3.8

slate swan
#

there's stable versions upto 3.11 available now... consider upgrading to 10 or 11 since you are upgrading

#

what operating system do you use?

#

oh i think the apt repo is updated with 3.10

hushed galleon
#

if you're currently using the system-provided python, i would suggest installing pyenv or similar and have it compile 3.11 for you, that way you arent potentially breaking your system

vale wing
#

Python package can't be upgraded, cause different python versions are different packages

#

You can install new with sudo apt install python3.11 then you would have to do some path stuff and there you go

#

If you only run the bot on that server you should just use docker

#

I don't see a problem using docker for small applications

steady berry
#

how can i make very simple discord bot with slash command for for example /say text:hi and output is hi but its only example

frail notch
#

How can I make a user specific command?
so like in the same way that I can do @commands.has_role("Admin"), how can I do that but for a user ID (so that only my id can run the command)

sick birch
frail notch
#

Except it's not necessarily my server

#

(a bot that i have in 2-3 servers that i own) so that i can use on my alt too

sick birch
#

Worth a shot lol

upbeat otter
#

!d discord.ext.commands.is_owner

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
sick birch
#

But I know it does exist

sick birch
upbeat otter
#

.checks is only used for app_commands

frail notch
#

so to specify 2-3 id's?

upbeat otter
sick birch
frail notch
#

if ctx.member == id

sick birch
#

Do you have other owners as well?

#

Add them to your team on the dev dashboard

frail notch
#

alr

frail notch
#

yeah thats what i had in mind ty

upbeat otter
#

just use an iterable instead of that?

#

well but yea, robin's method is way better

upbeat otter
#

using an iterable isn't even a next level logic lmao

#

ok then how's that basic

waxen crest
#

@frail notch you can also specify owner_ids in your bot instance it takes a list so owner_ids=[123, 456, etc]

upbeat otter
#

if you used iterables, that would require an if statement too

spiral crypt
#

oh, how do you think I could get around that?

vale wing
#

When you sudo apt remove --purge --autoremove -y python on linux

#

Btw discord disabled slash commands

#

Funny how I got a bunch of ratelimit errors when they did it

slate swan
#

cant relate i just syuuuuuu my system

young dagger
#

What could I use to match different time units?

#
def convert(time):
    pos = ['s', 'm', 'h', 'd']
    time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600*24}

    for p in pos:
        if p in time:
            num = int(''.join([i for i in time if i.isdigit()]))
            return time_dict[p] * num
    return None```
spice jewel
#

I went to sleep but will try now, my guess is no it won’t.

slate swan
#

question... what format is the assets parameter? I know it says similar to Activity, but that's rich presence.
what works in this field?

#

do i need to use something like assets=discord.Activity.assets("image_name", "image_url")?

young dagger
#

duration_seconds = for database
duration_string = for embed

jade laurel
balmy bobcat
#

hi, I created a slash command that makes a poll with reactions

...
        msg = await interaction.response.send_message(embed=embed)
        for i in range(nb):
            await msg.add_reaction(options[i])
...

Is it normal that the bot doesn't add any reaction?

#

I'm new to slash commands

balmy bobcat
#

yes, it does

sick birch
#

Where is nb defined?

balmy bobcat
#

nb is the number of responses I submit , nb = len(reponses)

#

and options is a list containing the emotes from 1️⃣ to 🔟

#

I just want to know if it's linked to the response.send_message

#

or if the code I sent should work

sick birch
spice jewel
#

can anyone help with this still?

frail notch
#

How would I add a URL button on this command?```py
@bot.command()
def verify(ctx):
embed=discord.Embed(
title="Verify",
description=f"Verify with core bot`",
color=0x36393F)
await ctx.send(embed=embed, BUTTON TO URL)

hushed galleon
# frail notch How would I add a URL button on this command?```py @bot.command() def verify(ctx...

assuming you're using discord.py 2.0 or a fork of that version (like disnake), you'd construct a discord.ui.View instance which will contain the message components, then add your URL button to it and send a message with that view: ```py
view = discord.ui.View()

button = discord.ui.Button(label="Google", url="https://www.google.com/")
view.add_item(button)

await ctx.send(..., view=view)``` (URL buttons are a unique case where the above syntax is acceptable, other kinds of buttons would be better suited for the subclass/decorator syntax)
other examples are in their repository:
https://github.com/Rapptz/discord.py/tree/master/examples/views

#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
frail notch
#

thanks

young dagger
#

@sick birch What is a good way to check if any mutes have expired. If a mute has expired, the bot should unmute the user?

sick birch
#

What mechanism are you using to mute? The old way or discord's new timeout feature?

young dagger
sick birch
#

Hm, fair enough

young dagger
#

I'm currently using the timeout feature. But the problem is you cannot mute people for longer then 1 week.

sick birch
#

Generally people just do

# apply mute to user
await asyncio.sleep(time)
# remove mute
#

But I can see problems with that approach for long mutes

young dagger
#

What about background task that runs periodically and checks if any mutes have expired?

sick birch
#

Nah
That has potential to keep a user timed out longer than they should

#

The more robust solution would be to store expiration in a database
And on startup load the expiriation - current_time, an asyncio.sleep() that duration

spice jewel
#
await ctx.send(":001callisto: **WARNING: This will remove the user entirely from the system, would you like to proceed?** :001callisto:")
msg1 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
    if msg1.content == "y":
        await ctx.send("What is the reason for removing?")
        msg2 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
        await member.remove_roles(defined_roles)
        await member.edit(nick=None)
        dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
        remove=discord.Embed(
            title=f"User Removed - {member.tag} ✦", 
            timestamp=datetime.datetime.utcnow(),
            color=discord.Color(0xac0101)
                )
        remove.add_field(
            name="User ID:",
            value=f"``{member.id}``"
                )
        remove.add_field(
            name="Reason:",
            value=msg2.content,
            inline=False
                )
        remove.set_footer(text=f'{member.id}')
        await ctx.send(embed=remove)```
spice jewel
sick birch
#

And it just hangs here?

#

Mm. on_ready not being triggered?

#

Hm. Do you have any error handling set up?

#

No, don't

#

I ask because usually people don't write error handlers properly
And it doesn't show anything in console

#

Then I'm left troubleshooting for 20 minutes before I realize they have a shoddily written error handler

#

But uh, could just be a temporary discord issue. They've been having a quite a few of those lately

#

Something seems to be off

vocal snow
#

it was resolved

slate swan
#

you might have something blocking in the setup hook if nothing after logging with static token gets executed

sick birch
#

Could be as setup_hook is one of the first things to be called

#

Can we see your setup hook?

#

You probably don't have one if you have client = commands.Bot

primal token
sick birch
#

Usually people use it with a subclass

#

I'm not seeing a setup hook

#

Same exact code?

#

If you're on VCS make sure they're on the same branch and have latest commits

#

What are your curling?

#

See if ping 8.8.8.8 goes through

#

Ah ping goes through fine

#

I can't tell if that's a successful ping or not

hushed galleon
sick birch
#

Something is off with your server then

#

Is it a self hosted server or is it cloud?

#

i would check with customer support then

#

"little vps" generally have this sort of issue

#

I'm gonna shill AWS then

#

I use it for my sites, bots, domains, emails + works great

#

but hetzner is great as well

#

average cloud provider experience

#

understandable

steep wedge
#

Solution: don’t use a VPS and surrender all of your Brain cells

young dagger
#

Is this a good solution to handle durations accurately?

    elif duration_seconds < 86400:
        hours = duration_seconds // 3600
        if hours == 1:
            return "1 hour"
        else:
            return f"{hours} hours"
    else:
        days = duration_seconds // 86400
        if days == 1:
            return "1 day"
        elif days < 7:
            return f"{days} days"
        else:
            weeks = days // 7
            remaining_days = days % 7
            if remaining_days == 0:
                return f"{weeks} weeks"
            else:
                return f"{weeks} weeks and {remaining_days} days"```
#

I don't want 15 days to be displayed as 2 weeks etc

fiery rain
#

Hey, could anyone help me use discord slash in my code? I haven’t coded in a while, and can’t find how to import it into my code, or what module to use.

naive briar
#

There's an example in the pins

fiery rain
#

Alright ty

young dagger
#

😢

naive briar
#

!e

seconds = 734856

minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)

print(f"""Seconds: {seconds}
Minutes: {minutes}
Hours: {hours}
Days: {days}
Weeks: {weeks}""")
unkempt canyonBOT
#

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

001 | Seconds: 36
002 | Minutes: 7
003 | Hours: 12
004 | Days: 1
005 | Weeks: 1
naive briar
young dagger
#

@naive briar Did you check the code?

naive briar
#

I did, and I don't know what it even does in the way it's written

young dagger
naive briar
#

!e

def add_s(n: int) -> str:
    return 's' if n > 1 else ''

seconds = 734856

minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
weeks, days = divmod(days, 7)

print(f"""Second{add_s(seconds)}: {seconds}
Minute{add_s(minutes)}: {minutes}
Hour{add_s(hours)}: {hours}
Day{add_s(days)}: {days}
Week{add_s(weeks)}: {weeks}""")
unkempt canyonBOT
#

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

001 | Seconds: 36
002 | Minutes: 7
003 | Hours: 12
004 | Day: 1
005 | Week: 1
naive briar
#

Why don't you just use Discord's timestamp anyway

#

<t:1675318701:R>

hushed galleon
young dagger
sick birch
#

timedelta parsing is always a royal pain in the arse

young dagger
hushed galleon
#

if defined_roles is a list, as i can only guess by the variable name, you should be getting an AttributeError: 'list' object has no attribute 'id' error because Member.remove_roles() doesnt take a list, but not seeing an error would also suggest you have an on_command_error that's suppressing the error message

of course, i could also be wrong if defined_roles is just a Role object, but that's omitted from your code

#

also worth pointing out that you have two inconsistent references of datetime.now() and datetime.datetime.utcnow() - only one of these will work depending on how you imported the datetime module

spice jewel
hushed galleon
young dagger
slate swan
young dagger
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
fading marlin
flat pier
torn sail
#

Can you inherit from commands.HybridGroup in the same way you can inherit from commands.GroupCog?

candid jacinth
#

are we allowed to self promote or invite people to test our bots on a separate channel? (looking for guinea pigs for a GPT DC Chatbot)

slate swan
#

1st : no
2nd: that depends on the user

fading marlin
torn sail
fading marlin
#

Subcommands inherit all of the default perms of its parent (you can't have specific perms for specific subcommands)

torn sail
#

guess ill just not use groups lmao

#

thanks tho

candid jacinth
#

If anyone would like to join my server for some testing I would appreciate it.
I just want to see that server permissions and stuff work right.
the GPT model is text-davinci-003 with midjorney in there too.

fading marlin
#

!rules 6

unkempt canyonBOT
#

6. Do not post unapproved advertising.

candid jacinth
fading marlin
#

You're welcome?

candid jacinth
#

Again if anyone would like to help let me know !

spice jewel
spice jewel
#

type object 'member' has no attribute 'tag'
File "/Users/myname/Custom bot/main.py", line 194, in remove
title=f"⠀⠀ User Removed - {discord.Member.tag} ✦",
^^^^^^^^^^^^^^^^^^
File "/Users/myname/Custom bot/main.py", line 222, in <module>
spooky.run(bot_token)
AttributeError: type object 'member' has no attribute 'tag'

#

@hushed galleon

fading marlin
#

You need an instance, not the class

smoky sinew
#

it's discriminator, don't guess random fields

smoky sinew
#

np, look at what lee said though, discord.Member refers to the class, it can't tell what member you are talking about

spice jewel
#

will do!

torpid hare
#

Hello can someone help me with something i want to display a set of 10 items and i want to have 2 emojis on the embed right and left arrow when you hit the right arrow you go to a new set of links and when you hit the left arrow you go back to the other links

wraith meteor
#

Hi all, i have one question
how to run function from module
the function

@bot.command(name='hi')
async def SendMessagehi(ctx):
    await ctx.send('Hello') 

how call from another programm module to send Hello to discord chat?
Thanks

flat pier
wraith meteor
#

hmm) looking in google 5 min ago for this silution, how python block code makes?

smoky sinew
#

use Context.invoke

wraith meteor
#

@slate swan

smoky sinew
#

ok?

#

what about it

wraith meteor
#

will try, ok, thanks:)

proper cliff
#

any way to check if sparkles is in the embd

#

i have the whole code just need help with regex

slate swan
#

!d discord.Embed.description

unkempt canyonBOT
#

The description of the embed. This can be set during initialisation. Can only be up to 4096 characters.

slate swan
#

if "✨" in embed.description: ...

proper cliff
#

lemme try

#

works ty

flat pier
#

You can also check against the emojis unicode directly iirc: \U00002728

slate swan
#

right, that's a better way

proper cliff
#

using regex?

#

ive no idea how to work with emojis

slate swan
#

nah, thats just a unicode

#

!charinfo ✨

unkempt canyonBOT
slate swan
#

its's basically the same thing ( usually)

#

if you use "\u2728" it will output the sparkles emoji

#

!e print ("\u2728")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

waxen crest
#

I'm making a custom embed parser, and \n isn't actually making a new line and instead just having \n in the code?

vale wing
#

.replace("\\n", "\n")

pulsar bridge
#

Trying to send an image to discord without saving it (Using Pillow)

    font = ImageFont.truetype("font.ttf", 28, encoding="unic") # Define Font
    bg = Image.new('RGB', (x, y), "black") # Creates the image
    at = ImageDraw.Draw(bg) 
    at.text((5, 5), text, (255, 255, 255), font=font) # Adds the text
    bg.show()
    f = bg.to_file() # <- Error
    await interaction.response.send_message(file=f)

This is what I have, but I'm getting an error.

File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 851, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "directory\bot.py", line 622, in textimage
    f = bg.to_file()
  File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\PIL\Image.py", line 517, in __getattr__
    raise AttributeError(name)
AttributeError: to_file

The above exception was the direct cause of the following exception:
  File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "\\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\app_commands\commands.py", line 869, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test_image_text' raised an exception: AttributeError: to_file

Ideas?

slate swan
#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
slate swan
#

!d PIL.Image.Image.save

unkempt canyonBOT
#

Image.save(fp, format=None, **params)```
Saves this image under the given filename. If no format is specified, the format to use is determined from the filename extension, if possible.

Keyword options can be used to provide additional instructions to the writer. If a writer doesn’t recognise an option, it is silently ignored. The available options are described in the [image format documentation](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html) for each writer.

You can use a file object instead of a filename. In this case, you must always specify the format. The file object must implement the `seek`, `tell`, and `write` methods, and be opened in binary mode.
slate swan
#
image = your pillow image
image.save(buffer_io:=io.BytesIO(), "PNG")

file = discord.File(buffer_io, "filename.png")
pulsar bridge
#

Thanks again, Vanessa!

charred badge
#

So I’m trying to reduce the length of my code. To do so I’m trying to implement aliases. A couple of them work but I cannot for the life of me figure out why on some they keep saying there is no command by “apex” anyone have any idea?

#

I thought maybe spaces were the issue, but other ones with spaces work fine

sick birch
#

Not sure why the other ones work, they shouldn't

charred badge
#

Aliases are the same way?

sick birch
charred badge
pulsar bridge
# slate swan ```py image = your pillow image image.save(buffer_io:=io.BytesIO(), "PNG") file...

Not working...
I've probably just done something wrong.

    channel = interaction.channel
    font = ImageFont.truetype("font.ttf", 28, encoding="unic")
    bg = Image.new('RGB', (x, y), "black")
    addtext = ImageDraw.Draw(bg)
    addtext.text((5, 5), text, (255, 255, 255), font=font)
    bg.show()
    bg.save(buffer_io:=io.BytesIO(), "PNG")
    f = discord.File(buffer_io, "testimagetext.png")
    await channel.send(file=f)

Sends a blank, 0 Byte file.

vale wing
vale wing
#

After you save to it

pulsar bridge
#

Just that?

vale wing
#

Yes

pulsar bridge
#

We have success!
Thanks again Vanessa, thanks Exenifix!

vale wing
#

Still thinking why is sarth vanessa now

slate swan
slate swan
smoky sinew
#

@slate swan

slate swan
#

yes?

smoky sinew
#

nothing

wraith meteor
#

have any other ideas how to run nextcord bot def in other way, not invoke becouse this is not external sourse, this is one multi module program?

smoky sinew
wraith meteor
#

i dont need to collect new task, just run one of nextcord bot def
like
@bot.command(name='year')
async def SendMessage(ctx):
await ctx.send(year)
form discord yeat return to you the year, so
i need to call this from another module of program, and get the year in discord chat

naive briar
#

What is collect new task

wraith meteor
#

invoke is task collector 🙂

naive briar
#

Huh ducky_sus

flat pier
naive briar
#

Weird

flat pier
#

i mean, either use Bot.invoke (or Context.invoke) or move the function of the command into a function and import it to wherever else you need to use it

naive briar
#

Is this undocumented or am I insane ducky_sus

flat pier
#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function...
wraith meteor
#

invoke just calls a command with given arguments though
yes, i am not found this on examplaes...

unkempt canyonBOT
#

discord/ext/commands/core.py lines 1014 to 1023

async def invoke(self, ctx: Context[BotT], /) -> None:
    await self.prepare(ctx)

    # terminate the invoked_subcommand chain.
    # since we're in a regular command (and not a group) then
    # the invoked subcommand is None.
    ctx.invoked_subcommand = None
    ctx.subcommand_passed = None
    injected = hooked_wrapped_callback(self, ctx, self.callback)  # type: ignore
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore```
naive briar
#

I swear this exists

#

They does handle converters for you here 😎

wraith meteor
#

sorry i'm badhead

vale wing
#

Hooked wrapped callback

wraith meteor
#

thanks to all

grizzled crown
#

does anyone have a list of good open source discords bots to reference?

#

want to get a good base to start off on

smoky sinew
#

red

#

python bot

#

red might not be the best example it's very big

grizzled crown
#

is that like a portfolio of discords bot?

slate swan
#

these are beginner friendly ( mostly )

grizzled crown
#

thanks checking them out now 🙂

slate swan
#

oops i misread your question

grizzled crown
#

yeah not at that stage yet lol

slate swan
#

What do I do to get the bot name

naive briar
#

bot.user.name

#

!d discord.Client.user

unkempt canyonBOT
slate swan
#

Anyway to make a button only clickable by a certain role with @discord.ui.button

vale wing
#

I mostly have bots in organisations

cobalt barn
#

help what do i do?

naive briar
#

Read the error

cobalt barn
#

i followed this tutorial

naive briar
#

!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.

cobalt barn
naive briar
#

Outdated

cobalt barn
#

ah

spice jewel
#

how can I make a discord bot add a reaction each time a message is sent in a specific channel

naive briar
#

!d discord.on_reaction_add

#

Whoops

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
naive briar
#

!d discord.Message.channel

unkempt canyonBOT
naive briar
#

Check the channel ID or whatever

spice jewel
# jade laurel why would you want to make it

good question, I'm programming a system and part of it requires a user to react to the message sent on command in the defined channel, so each time a message is sent the bot should automatically add a reaction there

jade laurel
#

Wouldn't it be smarter to just add a reaction whenever a command is used at this point.

shrewd fjord
#

Ig

spice jewel
jade laurel
#

what's the point of it

shrewd fjord
#

!d discord.Client.wait_for

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**...
shrewd fjord
#

@slate swan

slate swan
shrewd fjord
slate swan
#

kkk

static thunder
#

how to get the user who add the bot in server'

#

by audit log

shrewd fjord
unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
shrewd fjord
# unkempt canyon

You can separate all other actions by comparing bot adding action with entry.action

static holly
#

hi, why i have a infinite loop?

@commands.Cog.listener()
    async def on_message(self, message,  *, member_mention:discord.Member=None):

        
        user= message.author.mention

        if message.author==bot:
            return
            
        if member_mention == None:
            if message.content.startswith("bonjour"):
                await message.channel.send(f"Bonjour {user}")
            else:
                await message.channel.send(f"Bonjour {member_mention}")
            


        
            if message.content.startswith("Bonjour"):
                await message.channel.send(f"Salut {user}")
            else:
                await message.channel.send(f"Salut {member_mention}")



            if message.content.startswith("Bonsoir"):
                await message.channel.send(f"Bonsoir {user}")
            else:
                await message.channel.send(f"Bonsoir {member_mention}")



            if message.content.startswith("bonsoir"):
                await message.channel.send(f"Bonsoir {user}")
            else:
                await message.channel.send(f"Bonsoir {member_mention}")
            
vocal snow
#

message.author == bot.user

#

message.author == bot will always be False

static holly
static holly
vocal snow
#

on_message doesn't have member_mention:discord.Member=None parameter

#

it only takes message

#

if you want to get the mentions in the message you can use message.mentions

#

although not sure why it is looping. Can you share your code?

naive briar
#

It seems like you're in a cog

#

It should be like self.bot or something

slate swan
#

bot is an commands.Bot instance

naive briar
slate swan
#

you're looking for the ClientUser instance to compare with the author

#

!d discord.Client.user

unkempt canyonBOT
shrewd fjord
#

None if not logged in pithink

static holly
shrewd fjord
#

Printing Client.user before running it would return None

static holly
# slate swan you're looking for the ClientUser instance to compare with the author

yes I am looking to do this because I feel like my bot is responding to itself. so I would like to find the solution so that this is not the case and that it stops responding to itself, I have searched no matter how I can't find the solution and since I am still limited in the code sometimes I don't really understand what I'm doing so if someone could possibly guide me that would be really nice

static holly
vocal snow
static holly
vale wing
#

Code must be dry!

slate swan
slate swan
vale wing
#

!d discord.Message.content

unkempt canyonBOT
shrewd fjord
#

Unicode char 💀

vale wing
#

Empty string

shrewd fjord
#

It can be None anyway

vale wing
#

Ah yes system messages

#

But in docs it's str not Optional[str]

#

So it can't be None

tough lance
#

Hi, I needed help with top.gg api, if anyone here has some experience with that.

#

top.gg uses webhooks, so I created a POST route on my flask app

#

I just wanted to know how to authorize it.

slate swan
#

yeah it can't be None

#

confused with hikari for 3rd time in day ™️

unkempt canyonBOT
#

topgg/http.py lines 105 to 109

headers = {
    "User-Agent": self.user_agent,
    "Content-Type": "application/json",
    "Authorization": self.token,
}```
slate swan
#

the second and third one are needed in your case

tough lance
#

oh thanks

tough lance
#

@slate swan ^

slate swan
#
await post("/endpoint", headers={"Authorization": "your client token","Content-Type": "application/json"})
vale wing
vale wing
static holly
upbeat otter
shrewd fjord
#

only message kwarg

upbeat otter
#

arg

static holly
upbeat otter
static holly
upbeat otter
#

if that is what identifies as member_mention in the code

static holly
upbeat otter
#

which condition

#

because I'm unable to open pastebin again for some reason

#

skullcry why does pastebin suck so much

slate swan
#

use raw lol

static holly
upbeat otter
static holly
#

before, i has this code:

@commands.Cog.listener()
    async def on_message(self, message):

        if message.content.startswith("bonjour"):
            await message.channel.send(f"Salut {message.author.mention}")
        
        if message.content.startswith("bonsoir"):
            await message.channel.send(f"Salut {message.author.mention}")


        if message.content.startswith("Bonjour"):
            await message.channel.send(f"Salut {message.author.mention}")
        
        if message.content.startswith("Bonsoir"):
            await message.channel.send(f"Salut {message.author.mention}")
upbeat otter
#

so how is this relating to member_mention

static holly
#

but I want to add my condition that if I mention a member, the message must be different

upbeat otter
#

you can access the mentions using message.mentions

#

it will return a list of User objects

static holly
upbeat otter
#

in the on_message 💀

static holly
#

sorry 😕

upbeat otter
static holly
#

I know how to write some basic commands, make embeds, but from there to create a complex bot, I am not capable of it

upbeat otter
#

hm, that's fine then, goodluck

vocal snow
static holly
#

I don't know if it's said like that in English...

vocal snow
#

you're not completely wrong, but there's a lot more about them you should know

static holly
#

I should try to understand better with tutorials in French.

tough lance
slate swan
tough lance
#

I did.

slate swan
#

because that's what the "Authorization" value in headers will come from

tough lance
#

That's the problem, I did set up here but it is still returning None

slate swan
#

can we see more of your code?

tough lance
#
@app.route("/topsecrect/getvotes", methods=["POST"])
def votes():
    a = request.headers.get("Authorization")
    if a=="youshallnotpass":
        print("Yes")
    else:
        abort(401)
slate swan
#

oh, where does the request variable come from?

tough lance
#

from flask import request

heady verge
#
        buser = await bot.fetch_user(user.id)
        b_embed = discord.Embed(color=c.random(), title=f'{user.name}\'s Banner')
        b_embed.set_image(url=f'{buser.bannner}')```

`AttributeError: 'User' object has no attribute 'bannner'`
slate swan
heady verge
#

oops ty

slate swan
# tough lance It is.

hm it seems like flask works that way
can you try printing the headers and see if your token is part of some other header here

tough lance
#

I've got my whole site in that app

slate swan
#

yep, i just wasnt aware

tough lance
#

It returns everything other than authorization

#

weird part is when I send a custom request from another script, it does get the headers

slate swan
#

interesting, lemme try it

heady verge
#

is there a way to change the style of the button after it has been clicked

tough lance
#

<button obj>.color = ButtonStyle.<you choice>, then edit the message with view object

heady verge
#

okay!

vale wing
pulsar kettle
#

Attempting a server info command, received this error upon execution:
discord.app_commands.errors.CommandInvokeError: Command 'serverinfo' raised an exception: AttributeError: 'Guild' object has no attribute 'region'

@bot.tree.command(name = "serverinfo", description = "Provides information on the server")
async def serverinfo(interaction: discord.Interaction):
    guild = interaction.guild
    embed = discord.Embed(title = f"{guild.name} Info", description = "Information of this Server", color = 0xf6ff00)
    embed.add_field(name = "Server ID", value = f"{guild.id}", inline = True)
    embed.add_field(name = "Created On", value = guild.created_at.strftime("%b %d %Y"), inline = True)
    embed.add_field(name = "Owner", value = f"{guild.owner}", inline = True)
    embed.add_field(name = "Members", value = f'{guild.member_count} Members', inline = True)
    embed.add_field(name = "Channels", value = f'{guild.text_channels} Text | {guild.voice_channels} Voice', inline = True)
    embed.add_field(name = "Region", value = f'{guild.region}', inline = True)
    embed.set_thumbnail(url = guild.icon.url)
    embed.set_author(name = f'{interaction.author.name}', icon_url = {interaction.message.author.avatar.url})
    await interaction.response.send_message(embed=embed)```
Any help would be great <3
tough lance
#

That's what I've been doing.

vale wing
#

Then why do you say "it doesn't work like that"

tough lance
#

It was a question

vale wing
#

English is weird then

tough lance
#

I did add a question mark lol

slate swan
# tough lance weird part is when I send a custom request from another script, it does get the ...
import flask, random
from flask import request

app = flask.Flask(__name__)

@app.route("/")
def home():
  return "yo"

@app.route('/vote', methods=["POST"])
def vote_add():
  assert request.headers.get("Authorization") == "#mypassword"
  print("works")

# running the app
``` output: ```sh
 * Serving Flask app 'main'
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:4686
Press CTRL+C to quit
172.31.128.1 - - [25/Jan/2023 13:55:54] "GET / HTTP/1.1" 200 -
works
#

works for me

#

i did a test vote from the "send test" option

pulsar kettle
slate swan
#

i have discord.py installed by the module is not detected

Requirement already satisfied: aiohttp<4,>=3.7.4 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from discord.py) (3.8.3)
Requirement already satisfied: attrs>=17.3.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (22.2.0)
Requirement already satisfied: charset-normalizer<3.0,>=2.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (2.1.1)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (6.0.4)
Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.8.2)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.3.3)
Requirement already satisfied: aiosignal>=1.1.2 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from aiohttp<4,>=3.7.4->discord.py) (1.3.1)
Requirement already satisfied: idna>=2.0 in c:\users\gabriel\appdata\local\programs\python\python311\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<4,>=3.7.4->discord.py) (3.4)
PS C:\Users\Gabriel\Desktop\projetos python> & "c:/Users/Gabriel/Desktop/projetos python/venv/bin/python.exe" "c:/Users/Gabriel/Desktop/projetos python/RP Utilities/rp_main.py"
Traceback (most recent call last):
  File "c:/Users/Gabriel/Desktop/projetos python/RP Utilities/rp_main.py", line 1, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'```
naive briar
#

Are you using virtual environment

#

Seems like it ducky_sphere

slate swan
#

from this one:

#

VS code

naive briar
slate swan
#

okay

#

before anything, i'm using windows, will it work?

#

the venv to install on it?

heady verge
#

how to display the username of the user including their name and discriminator

vale wing
pulsar kettle
#

I think that's why it gives me that error

slate swan
#

the members and channels fields can be way too long ... you might want to slice them off

slate swan
#

the max chars you can have is 1024

pulsar kettle
#

So how do i change it to just display the total amount of text/voice channels

embed.add_field(name = "Channels", value = f'{guild.text_channels} Text | {guild.voice_channels} Voice', inline = True)```
slate swan
#

!d len

unkempt canyonBOT
#
len

len(s)```
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

**CPython implementation detail:** `len` raises [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") on lengths larger than [`sys.maxsize`](https://docs.python.org/3/library/sys.html#sys.maxsize "sys.maxsize"), such as [`range(2 ** 100)`](https://docs.python.org/3/library/stdtypes.html#range "range").
slate swan
#

guild.text_channels is a list ( same for .voice_channels), using len gives you the number of items in it

pulsar kettle
#

Ah I see, thanks
I also get the error discord.app_commands.errors.CommandInvokeError: Command 'serverinfo' raised an exception: AttributeError: 'Guild' object has no attribute 'region' when this line is added:

 embed.add_field(name = "Region", value = f'{guild.region}', inline = True)```
#

Is {guild.region} incorrect?

naive briar
#

They removed it

pulsar kettle
#

Oh they did?

naive briar
#

To my knowledge, anyways

slate swan
#

okay, i tried to execute this and this happened

#

translation: the system cannot find the specified path

slate swan
#

notice the . before environment name

#

oh actually that's not it

slate swan
pulsar kettle
#

Is it possible to find the amount of boosts a server has or nah? Cuz I searched "boost" on the discord.py api and I got nothing

slate swan
slate swan
pulsar kettle
slate swan
#

if yes, try the other env script variants ( ps1 and the other one ) instead of bat

hushed galleon
#

i suggest running dir env\Scripts to check, but i cant think of a reason why virtualenv wouldn't generate the corresponding batch file for activation...
btw this should go in a help post on #1035199133436354600

slate swan
unkempt canyonBOT
#
Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
hollow gazelle
#

!treecommands

#

!add_command

#

im tryna to add options to tree commands anyone help?

naive briar
#

Pins

hollow gazelle
naive briar
#

In THE PIN

hollow gazelle
#

ohhhh

#

how far down

vocal snow
hollow gazelle
#

thanks

#

so i got @bot.tree.command
and @strange knoll_commands idk what to add to make it a option

vocal snow
#

make what an option

hollow gazelle
#

holdon

#

so it looks like that

vocal snow
#

just make a parameter on the command callback

hollow gazelle
#

ok

hollow gazelle
#

thanksd

outer flint
#

what do you think it's the best way to retrieve #, User, Messages, Exp, Level from a MEE6 leaderboard?

        url = "https://mee6.xyz/en/leaderboard/779531957222375455"
        page = requests.get(url)
        soup = BeautifulSoup(page.content, "html.parser")

        # Find the div containing the leaderboard data
        div = soup.find("div", class_="leaderboard-list")
        print(div)

        # Create an empty list to store the data
        data = []

        # Extract the data
        for i in div.find_all("div", class_="leaderboard-list-item"):
            rank = i.find("div", class_="leaderboard-list-item-rank").text
            user = i.find("div", class_="leaderboard-list-item-username").text
            messages = i.find("div", class_="leaderboard-list-item-messages").text
            exp = i.find("div", class_="leaderboard-list-item-exp").text
            level = i.find("div", class_="leaderboard-list-item-level").text
            data.append([rank, user, messages, exp, level])

        # Create a csv file and write the data to it
        with open("leaderboard.csv", "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerow(["#", "User", "Messages", "Exp", "Level"])
            writer.writerows(data)

        print("Data saved to leaderboard.csv")

I was thinking about something like this, but the div found it always empty

static thunder
#

What is the audit log event for discord bot add

shrewd fjord
hushed galleon
unkempt canyonBOT
shrewd fjord
#

you can check if the member is bot or not if it's use this...

#

....

#

Oh typo

#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
shrewd fjord
static thunder
#

Then

shrewd fjord
#

....;-;?

static thunder
#

Thenks*

shrewd fjord
#

!d discord.AuditLogAction.bot_add

unkempt canyonBOT
shrewd fjord
#

Works too

hushed galleon
#

ah, didnt know that action exists too

shrewd fjord
slate swan
slate swan
#

check the Scripts folder of your env to see if the activate files are even there or not

shrewd fjord
#

vanessa Peepo_UwU

slate swan
#

when i checked up it brings me this:

#

guess all i had to do is to change script to bin

timid spade
#

can someone tell me what are these different types of selects

slate swan
#

probably because you're using virtualenv instead of the built-in venv module

slate swan
slate swan
slate swan
#

how do i create a venv file without the linux version?

#

use venv 🤷‍♂️

#

python -m venv env

#

how to install the windows version of venv?

#

it kinda erroed here

#

it comes preinstalled

#

yeah, it's built in

#

what version of python do you use?

#

i kinda updated it but it shows 3.8.9

tough lance
#

If not then you can always do pip install virtualenv

slate swan
#

how do i delete the old version to use the updated version?

slate swan
#

or you can mention the full version name if you dont want to delete the old installation

#
python3.<version> -m venv env
#

how do i delete the old version

#

and check the new version?

tough lance
#

and then install from official python website

#

Also this is kinda ot

slate swan
#

back to the problem i had before:

cold sonnet
#

await random.choice(guild.text_channels).send("random shit")

hushed galleon
frail notch
waxen crest
frail notch
#

so... @command(owner_ids)?

waxen crest
frail notch
#

oooh

waxen crest
frail notch
#

yea like in the python file

waxen crest
frail notch
#

oh kkk

#

tyy

#

could i do bot = commands.Bot(..., owner_ids=list(owners.json)?

waxen crest
frail notch
#

alr

tawny junco
#

What does owner_ids do? You can have other people own the bot??

tawny junco
#

What additional functionality would they get by doing so?

waxen crest
frail notch
#

would this also work?

tawny junco
#

I see

waxen crest
frail notch
#

kk ty

waxen crest
frail notch
#

wait lemme remove []

#

yea

tawny junco
waxen crest
waxen crest
tawny junco
#

Bet

waxen crest
#

?!

tawny junco
#

Nuh-uh.

#

Rejection〜

waxen crest
tawny junco
#

I see I see

waxen crest
# tawny junco I see I see

Yeah I'm about to do that nonsense.. people have been asking for a feature that would cost me money so I'm going to make it premium. I don't like making paid features but when I have to pay, I rather make it premium

arctic fiber
#

Would I put that in the main file for the bot?

vocal snow
#

if that's where you're calling client.run, sure

arctic fiber
#

How do I fix this?

deep osprey
#
class MyView(View):
    @discord.ui.button(label="Click to copy!", style=discord.ButtonStyle.secondary, emoji="✔")
    async def button_callback(self,button,interaction):
        button.label = "Copied!"
        button.disabled = True
        button.style = discord.ButtonStyle.green
        await interaction.response.edit_message(view=self)```

```    button.label = "Copied!"
AttributeError: 'Interaction' object has no attribute 'label'
fading marlin
#

Switch the arguments around

- (self, button, interaction)
+ (self, interaction, button)
deep osprey
#

worked now thanks!

vale wing
arctic fiber
#

I was looking at the python docs

arctic fiber
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

vocal snow
#

there are a lot of free resources for learning python there ^

zinc sluice
#

does anyone know what the problem is? i did everything like in the tutorial and the guy on youtube is online but mine doesn´t work

cloud dawn
#

@vocal snow still at it, absolute mvp.

#

How do you have so much time, tell me the secret.

#

Well the first one is that role isn't loaded or just doesn't exists. Second one is that the bot doesn't have permission to do the action inside the command.

zinc sluice
#

where do i enable them? in discord or in replit?

vocal snow
cloud dawn
cloud dawn
vocal snow
#

yeah its an acquired taste without the milk

cloud dawn
#

I'm very busy with an internship now, else I would def help out more here.

vocal snow
#

oh cool, python internship?

cloud dawn
#

For the API yes, paired with PostgreSQL + alembic and React, TS + chakra.

#

Learning so many new things :D

manic wing
#

Are you still waitering as well?

zinc sluice
cloud dawn
manic wing
cloud dawn
#

Internship is 36h/week and 1 day school so doing overtime already.

#

Saturday and Sunday free :)

manic wing
cloud dawn
#

Until May 31th, and most likely going straight to developer.

#

After this I need to hand in my report of the internship then if that's validated then I've graduated.

vocal snow
vocal snow
#

it's role needs to be higher than the top role of the user it's adding/removing roles to

#

are you adding to the server owner

#

the role you're trying to add needs to be lower than the bot's top role

slate swan
#

1 sec let me fix some thigns

vocal snow
#

good morning mudkip

smoky sinew
#

hello

#

how is college

vocal snow
#

good 👍

#

how is primary school

smoky sinew
#

wtf

vocal snow
#

i meant elementary school, apologies

smoky sinew
#

im not that young

sick birch
#

i wouldn't let that one slide

tame osprey
#

Hey guys can you help my with my code it has an Tab error?

vocal snow
tame osprey
#

i need to bee a day here

vocal snow
tame osprey
vocal snow
#

ok then, what's the error?

#

(the full error)

tame osprey
#

26.01 00:18:40 [Bot] Traceback (most recent call last):
26.01 00:18:40 [Bot] File "/main.py", line 7, in <module>
26.01 00:18:40 [Bot] from music_cog import music_cog
26.01 00:18:40 [Bot] File "/music_cog.py", line 99
26.01 00:18:40 [Bot] self.is_paused = False
26.01 00:18:40 [Bot] ^
26.01 00:18:40 [Bot] IndentationError: expected an indented block
26.01 00:18:41 [PebbleHost] Server shut down (running)
26.01 00:18:41 [PebbleHost] Server stopped

#

the full is too long

#

i know it shoud be a tab error but how can i fix that?

vocal snow
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

vocal snow
#

Also, we can't help with music bots here

tame osprey
#

all right, thank you anyway

#

thanks for the effort and have a nice day

slate swan
#

how can i make my bot accept an invite

vocal snow
#

you can't

slate swan
#

yes u can

vocal snow
#

discord bots cannot accept discord server invites

slate swan
#

they can

#

its how u make it a user bot

vocal snow
#

I assumed you were talking about a normal discord bot, since user bots aren't allowed by discord and we don't help with them here

slate swan
#

i mean it is a normal bot till it accepts invite then its a user bot sooooo

vocal snow
#

it's a user bot as soon as you log in with your user token

slate swan
#

that doesnt work

wary crystal
#

Can't believe people are still self-botting in 2023

#

Lmao

primal token
still heron
#

anyone have command

vocal snow
spice jewel
#

does anyone know how to display username/server name using sqlite db

vocal snow
spice jewel
#

basically want server names + user to display as the guild name and user name

#

rather then an integer

naive briar
#

Why is your server name an int

spice jewel
#

so I could still test the code

vocal snow
#

Are you sure you can have spaces in field names?

spice jewel
#

do you know how to make it display text (the server name/user name)?

naive briar
#

Set its type as TEXT

#

And you can't have spaces in the field name because SQLite use that to separate types (to my knowledge anyways)

spice jewel
ionic garden
#

ok, but discord.py, which requires aiohttp, is listed
should i pay attention to this warning?

vocal snow
smoky sinew
#

it just reminds me of andy

#

the name pfp and the message

ionic garden
#

alr

vocal snow
smoky sinew
#

actually i wouldn't be surprised if it was andy

vocal snow
#

also true

primal token
smoky sinew
#

💀

primal token
#

nopesalute

slate swan
#

any ideas on how to fix? Traceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/discord/client.py", line 409, in _run_event await coro(*args, **kwargs) File "/root/roof.py", line 247, in on_ready await tree.sync(guild = discord.Object(id=0)) File "/usr/local/lib/python3.9/dist-packages/discord/app_commands/tree.py", line 1071, in sync data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload) File "/usr/local/lib/python3.9/dist-packages/discord/http.py", line 738, in request raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

honest slate
#

How can I create a discord bot

slate swan
#

well what library do you want to use?

naive briar
slate swan
#

i have tried that but i will try agin.

#

again*

naive briar
#

And the guild ID in the tree.sync must be valid

#

Or exists, whatever

spice jewel
#
    await('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
TypeError: object tuple can't be used in 'await' expression```
#

does anyone know how to fix (sqlite)

naive briar
#

You're trying to await a tuple

#

Not a function

#

At least try to look where the error occurred

#

!e

import asyncio

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

async def main():
    await("meow",)

loop.run_until_complete(main())
unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 9, in <module>
003 |   File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
004 |     return future.result()
005 |            ^^^^^^^^^^^^^^^
006 |   File "<string>", line 7, in main
007 | TypeError: object tuple can't be used in 'await' expression
spice jewel
naive briar
#

Are you kidding me

spice jewel
#
data = await cursor.fetchone()
if data:
  await('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
else: 
   await(cursor.execute('INSERT INTO users (user, id, server_name, guild) VALUES (?, ?, ?, ?)', (f"{member.name} + #{member.discriminator}", member.id, ctx.guild.name, ctx.guild.id,))```
spice jewel
smoky sinew
spice jewel
smoky sinew
spice jewel
smoky sinew
#

a tuple is a data type, cursor.execute is an async function

shrewd fjord
#

Mhm

#

You need to refactor your code a bit

spice jewel
smoky sinew
#

that might be an SQL problem

#

i'm not familiar with sql stuff

shrewd fjord
#

Nope

#

You need to commit the changes

#

F

spice jewel
#

await db.commit()

shrewd fjord
#

Demn

shrewd fjord
#

On the if statement

spice jewel
spice jewel
naive briar
#

Show the full code

spice jewel
#

its really long but I will cut it down one sec

naive briar
#

You need to commit everytime when you want to change something in the database

spice jewel
#

I have

unkempt canyonBOT
#

Hey @spice jewel!

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

spice jewel
#

i

#

one second

#
        msg3 = await callisto.wait_for("message", check=lambda x: x.author == ctx.author)
        if msg3.content == "y":
            await ctx.send("![callistoalertdns](https://cdn.discordapp.com/emojis/1068000006344290406.webp?size=128 "callistoalertdns") User removed ![callistoalertdns](https://cdn.discordapp.com/emojis/1068000006344290406.webp?size=128 "callistoalertdns")")
            await ctx.send(embed=remove)
            dynamic_timestamp = nextcord.utils.format_dt(datetime.now(), style="R")
            removenotice=nextcord.Embed(
                title=f"⠀⠀ You were removed ✦", 
                color=nextcord.Color(0x8d06411)
                )
            async with aiosqlite.connect("callisto.db") as db:
                async with db.cursor() as cursor:
                    await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
                    data = await cursor.fetchone()
                    if data:
                        await cursor.execute('DELETE FROM users WHERE id = ? AND guild = ?', (member.id, ctx.guild.id,))
                        await cursor.execute('DELETE FROM pilots WHERE id = ? AND server_ids = ?', (member.id, ctx.guild.id,))
                await db.commit()
            await member.send(embed=removenotice)```
#

this is the part which had the previous traceback

#

can any of u still help w this?

slate swan
#
  File "/root/pres_d.py", line 6, in <module>
    RPC = Presence(client_id)
  File "/usr/local/lib/python3.9/dist-packages/pypresence/presence.py", line 13, in __init__
    super().__init__(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/pypresence/baseclient.py", line 28, in __init__
    raise DiscordNotFound
pypresence.exceptions.DiscordNotFound: Could not find Discord installed and running on this machine.``` any fixes
#

i have it running on a debian 10 vps so its a ssh.

sullen river
#

anyone know how to run a discord.client and a command.bot

slate swan
#

please @ me if yk what is wrong.

sullen river
#

anyone know?

sullen river
sullen river
naive briar
#

If you want to create prefix commands, just use discord.ext.commands.Bot

#

And delete the discord.Client

sullen river
#

alr

sullen river
naive briar
#

Yes

sullen river
#

alr cool

smoky sinew
#

what is the biggest python discord bot measured by LOC?

#

is it red??

sullen river
#

unless im doing it wrong.

shrewd fjord
smoky sinew
#

the commands extension was introduced years ago

sullen river
#

uhh

#

idk friend is helping me out

shrewd fjord
spice jewel
sullen river
smoky sinew
#

the command system

spice jewel
#

it just returns none

sullen river
#

or could u send me a command lines for example

#

an example*

smoky sinew
#

what library are you using

sullen river
pastel basin
#

I was reading the doc and saw this:

@bot.hybrid_command()
async def test(ctx):
    await ctx.send("This is a hybrid command!")

I have been maaking slash commands like this:

@client.tree.command(name="streak", description="Shows your current streak.")
async def slash_streak(interaction: discord.Interaction):

    with open ('data.json') as count:
        data = json.load(count)
        total_streak = data["streak"]

    await interaction.response.send_message(f"Your current streak is {total_streak}")

what's the difference?

naive briar
#

Hybrid gives you both slash and prefix command

pastel basin
pastel basin
#

well, i will use hybrid more

naive briar
#

No

pastel basin
#

easy syntax 😅

upbeat otter
#

it's the same

pastel basin
# upbeat otter it's the same
@client.tree.command(name="streak", description="Shows your current streak.")
#See the difference mate
@bot.hybrid_command()
smoky sinew
#

yes but you can also put that in hybrid_command

vale wing
#

Remove the kwargs and it will be almost the same

upbeat otter
#

^

pastel basin
#

my bad ...

smoky sinew
#
@client.tree.command()
#See the difference mate
@bot.hybrid_command()
pastel basin
#

feeling dumb now

#

need some sleep..... that's the reason

#

Sorry @upbeat otter

upbeat otter
#

oh it's fine 💀 you don't have to do that

spice jewel
upbeat otter
spice jewel
#
    await('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
TypeError: object tuple can't be used in 'await' expression```

which has now been resolved
sullen river
spice jewel
#

but whenever I try to add someone in my database

upbeat otter
spice jewel
upbeat otter
#

you can see that if you read the error carefully

shrewd fjord
#

Ash ayo

spice jewel
#

Ive fixed it yeah but now it doesnt do anything and when I get it to print the data it returns none

#

(after ive run the cmd)

upbeat otter
#

the update stuff

spice jewel
shrewd fjord
upbeat otter
#

spooky 🛐

shrewd fjord
#

if data:
Should have worked tii

#

Too pithink

shrewd fjord
spice jewel
#
        async def button6_callback(interaction):
            if interaction.user == ctx.author:
                view.remove_item(button6)
                await interaction.response.edit_message(content="Other added!", view=view)
        
        msgnext = await callisto.wait_for("message", check=lambda x: x.author == ctx.author)
        if msgnext.content == "next":
            await ctx.send("What is there starting vouch count?")
            msg2 = await callisto.wait_for("message", check=lambda x: x.author == ctx.author)
            if msg2.content == "test":
                async with aiosqlite.connect("callisto.db") as db:
                    async with db.cursor() as cursor:
                        await cursor.execute('SELECT id FROM users WHERE guild = ?', (ctx.guild.id,))
                        data = await cursor.fetchone()
                        if data:
                            await cursor.execute('UPDATE users SET id = ? WHERE guild = ?', (member.id, ctx.guild.id,))
                        else:
                            await cursor.execute('INSERT INTO users (user, id, server_name, guild) VALUES (?, ?, ?, ?)', (f"{member.name} + #{member.discriminator}", member.id, ctx.guild.name, ctx.guild.id,))
                            await cursor.execute('INSERT INTO pilots (pilot_vouches, games, user, id, server_ids) VALUES (?, ?, ?, ?, ?)', (0, f"none", f"{member.name} + #{member.discriminator}", member.id, ctx.guild.id,))
                    await db.commit()
                await ctx.send(embed=embed)```
#

ive cut down the code a bit

#

this is the part in my code I was getting the first error, but now when I run the add cmd and respond to the message correctly (test) it still doesn't add the user to the db but it sends the embed

shrewd fjord
#

Wait a sec

shrewd fjord
#

You need to use "" this it's the correct format for executing a query

#

"UPDATE....... ...." like dat

spice jewel
shrewd fjord
#

And use single quote on string/text values

shrewd fjord
#

!d sqlite3

spice jewel
#

still no

#

ahh

shrewd fjord
#

Mhm

spice jewel
shrewd fjord
#

instead of ?

spice jewel
#

still no tracebacks, no errors, nothing

#

just not adding the user

shrewd fjord
shrewd fjord
#

Altho it's not recommended, but this is pretty good for testing stuffs

shrewd fjord
naive briar
#

What's wrong with placeholders

shrewd fjord
#

Because it can't update the column if it returns None

shrewd fjord
#

But code is working fine but not working

#

Kinda spooky

spice jewel
#

sqlite3.OperationalError: no such table: users

#

I literally

shrewd fjord
spice jewel
#

have a table

shrewd fjord
#

Did u create table?

ionic garden
#
    @commands.hybrid_command(
        name="profile",
        description="Check a player's general information.",
        aliases=["p"]
    )
```is there any shortcut for when there's only one alias?
spice jewel
#
@callisto.event
async def on_ready():  
    print("Online!")
    async with aiosqlite.connect("callisto.db") as db:
        async with db.cursor() as cursor:
            await cursor.execute('CREATE TABLE IF NOT EXISTS middlemans(mm_vouches INTEGER, games TEXT, user TEXT, id INTEGER, server_ids INTEGER)')
            await cursor.execute('CREATE TABLE IF NOT EXISTS pilots(pilot_vouches INTEGER, games TEXT, user TEXT, id INTEGER, server_ids INTEGER)')
            await cursor.execute('CREATE TABLE IF NOT EXISTS users(user TEXT, id INTEGER, server_name TEXT, guild INTEGER)')
        await db.commit()```
spice jewel
shrewd fjord
#

There is some prob with commit then

spice jewel
shrewd fjord
#

Idk, weird stuffs 💀

spice jewel
#

(doesnt work)

shrewd fjord
upbeat otter
shrewd fjord
spice jewel
#

HELP

shrewd fjord
#

🙂