#discord-bots

1 messages · Page 150 of 1

fading marlin
#

if you've got your code on github, it should be fairly simple. If you don't have your code on github, you should add it to github lol.

in all seriousness, your library/package should include a LICENSE file where you add whichever license you want (MIT, Apache, etc)

honest shoal
#

10s

naive briar
#

Do you know how arguments work first of all 🐈

#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
gusty mango
honest shoal
fading marlin
#

holy smokes

gusty mango
fading marlin
#

that is a really unnecessary if/elif chain

gusty mango
naive briar
#

Remove the :

honest shoal
gusty mango
honest shoal
#

you didn't close the bracket + no colon

gusty mango
#

new pastebin

slate swan
#
@commands.has_permissions(administrator=True)
async def purge(ctx, limit: int):
        await ctx.channel.purge(limit=limit)
        await ctx.send('Cleared by {}}'.format(ctx.author), delete_after=10)
        await ctx.message.delete()

@purge.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You can't do that!", delete_after=10)``` it dosent send the message `Cleared by .......` and `You can't do that!` after i added delete_after
honest shoal
slate swan
gusty mango
gusty mango
honest shoal
naive briar
honest shoal
#

place it with other parameters in above line

naive briar
#

Wait, I misread a bit

fading marlin
gusty mango
slate swan
#

got any idea how to fix?

gusty mango
#

round_id = str(round_id):
async def mines(interaction: discord.Interaction, tile_amt: int,):

fading marlin
slate swan
#

and if i type 2 messages and type !clear 2 it will delete only one because the message !clear 2 counts in the clear

slate swan
#

and idk how to fix it

gusty mango
naive briar
honest shoal
gusty mango
slate swan
#

kk thx

honest shoal
#

It'll take 5 minutes

gusty mango
gusty mango
honest shoal
#

yes

white citrus
#

Where can I ignore this error if the bot does not have access to this channel?

  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 221, in on_message
    c = await bot.fetch_channel(int(servers['global_id']))
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 1729, in fetch_channel
    data = await self.http.get_channel(channel_id)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 391, in request
    raise Forbidden(response, data)
nextcord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
naive briar
#

!d discord.TextChannel.permissions_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
cedar fulcrum
#

#bot-commands

gusty mango
slate swan
#

like this?

white citrus
slate swan
#

catgal

naive briar
#

!d discord.ext.commands.Command.error

unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`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 limited to a single command. However, 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") is still invoked afterwards as the catch-all.

Changed in version 2.0: `coro` parameter is now positional-only.
naive briar
#

!d discord.ext.commands.Bot.on_command_error

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
naive briar
#

Or this for global

#

What

slate swan
peak pewter
#
@client.tree.command(name='user_info', description='gives you the info on the user you')
async def userinfo(interaction: discord.Interaction, member:discord.Member=None):
    if member==None:
        member = interaction.user
    roles = [role for role in member.roles]
    embed=discord.Embed(title=f'{member.name}#{member.discriminator}', description=member.mention, color=0x1eca37, timestamp = datetime.utcnow())
    embed.set_thumbnail(url=member.avatar)
    embed.add_field(name="__Registered__", value = member.created_at.strftime('%d/%m/%Y, %H:%M:%S'))
    embed.add_field(name="__Joined__", value = member.joined_at.strftime('%d/%m/%Y, %H:%M:%S'))
    embed.add_field(name='__Status__', value=member.status)
    embed.add_field(name="__ID__", value = member.id)
    embed.add_field(name=f'__Roles ({len(roles)-1} Roles)__', value=' '.join([role.mention for role in roles[1:]]))
    embed.set_footer(text='Created by UniqueDolphin#8001')
    await interaction.response.send_message(embed=embed)
#

When i am trying to tag a member it doesn't work

#

discord.app_commands.errors.CommandInvokeError: Command 'user_info' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.fields.4.value: This field is required

#

This is the error

naive briar
#

Field value is required

peak pewter
frosty umbra
#

bot.run(“token”)

#

If you have that at the end of your code then it means you have an error in your code

#

Token being your bots token

frosty umbra
#

You set discord.Member = None

peak pewter
#

what should i put there

frosty umbra
#

Remove the = None?

#

I dont really know what its doing

#

Hes setting it so that member is always None

#

discord.Member=None

#

No matter what anyone puts in there it will equal None

#

No?

#

member: discord.Member=None):

peak pewter
#

i think they are talking about
async def userinfo(interaction: discord.Interaction, member:discord.Member=None):

frosty umbra
#

Hes setting discord.Member to none here no?

#

I know

#

But hes setting it to always be none so his code will have issues later

#

Is it?

#

Didnt know it was a kwarg

peak pewter
#

@fallow jolt it is still giving me an error when i am trying to tag someone

#

discord.app_commands.errors.CommandInvokeError: Command 'user_info' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.embeds.0.fields.4.value: This field is required

#

This error

frosty umbra
#

Issue with the embed

peak pewter
#

yes lol

#

bro you are the best

slate swan
#

hi i got this code

#

but i want the bot to specify how much messages it deleted

#

so Cleared MESSAGES by {ctx.author}

#

any1 knows how

frosty umbra
#

What error you get

slate swan
#

need full error

frosty umbra
#

What

slate swan
#

whats line 1

frosty umbra
#

Show your code

slate swan
#

lol

#

what are the words in line 1

frosty umbra
#

import i assume

slate swan
#

yeah probably

peak pewter
slate swan
#

i dont think u have sum modules installed

#

yea pretty sure he is doing some sketch shit. the bot is named fake sniper

frosty umbra
#

Ok dm me it

slate swan
#

then the member is offline lol

frosty umbra
peak pewter
#
@client.tree.command(name='user_info', description='gives you the info on the user you')
async def userinfo(interaction: discord.Interaction, member:discord.Member=None):
    if member==None:
        member = interaction.user
    roles = [role for role in member.roles]
    embed=discord.Embed(title=f'{member.name}#{member.discriminator}', description=member.mention, color=0x1eca37, timestamp = datetime.utcnow())
    embed.set_thumbnail(url=member.avatar)
    embed.add_field(name="__Registered__", value = member.created_at.strftime('%d/%m/%Y, %H:%M:%S'))
    embed.add_field(name="__Joined__", value = member.joined_at.strftime('%d/%m/%Y, %H:%M:%S'))
    embed.add_field(name='__Status__', value=member.status)
    embed.add_field(name="__ID__", value = member.id)
    embed.add_field(name=f'__Roles ({len(roles)-1} Roles)__', value=' '.join([role.mention for role in roles[1:]]))
    embed.set_footer(text='Created by UniqueDolphin#8001')
    await interaction.response.send_message(embed=embed)
frosty umbra
peak pewter
#

the output of status is always offline

frosty umbra
#

Oh

#

Thats what you meant

peak pewter
#

embed.add_field(name='Status', value=member.status)

#

this line need fixing

frosty umbra
#

Member.status

#

wait nvm

slate swan
#

im pretty sure u need intents for that do u not

frosty umbra
slate swan
#

maybe not.

frosty umbra
#

Just checked

#

Intents.members should be enabled

slate swan
#

oh yea

#

nah

#

its presence

peak pewter
#

what?

slate swan
#

you need the presence intent

#

in order to get member status'

frosty umbra
#

Oh its presence true

#

Its a special intent so you have to enable it on your bot and in your code

frosty umbra
#

Bros stealing cookies smh

slate swan
#

lmfaooooo

frosty umbra
#

From 10 year olds

slate swan
#

thats why its called fake sniper

frosty umbra
#

Hes asking me why I cant just help him

slate swan
#

he tryna pass it as a vanity sniper bot and upload to gh

#

i hate ppl like that

frosty umbra
#

I have the source to the program and sure enough it sends cookie to webhook and checks what items they have

slate swan
#

smh

frosty umbra
#

If they have good items he’ll probably use it to steal from the kids

#

Also his code looks like its been stolen from someone elses github

livid void
#

He's ban ?

frosty umbra
#

He gave me his webhook too 💀

slate swan
#

lololol.

frosty umbra
white citrus
#
    @bot.event
    async def on_message(message: nextcord.Message):
        
        if message.author.id == bot.user.id:
            return
        else:
            _public_global_chat_check = await bot.settings.get_all({}, projections=Projection(Show("global_id")).build())
            
            if _public_global_chat_check is None:
                return
            
            if _public_global_chat_check is not None:
                
                _server_gl_cc_dict = {"_id": message.guild.id}
                _server_gl_cc = await bot.settings.find(_server_gl_cc_dict)
                
                if _server_gl_cc is None:
                    return
                
                if _server_gl_cc is not None:
                    
                    if message.channel.id == _server_gl_cc["global_id"]:
                        
                        for servers in _public_global_chat_check:
                            print(servers)
                            if "global_id" in servers:
                                c = await bot.fetch_channel(int(servers['global_id']))
                                try:
                                    await c.send(message.content)
                                except nextcord.Forbidden:
                                    continue
                                
                            else:
                                continue
                            
                        return()
                    
                    else:
                        return
                
        return```
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 221, in on_message
    c = await bot.fetch_channel(int(servers['global_id']))
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 1729, in fetch_channel
    data = await self.http.get_channel(channel_id)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 391, in request
    raise Forbidden(response, data)
nextcord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
#

how can i keep the loop running even if he doesn't have access to this channel

fading marlin
#

bot.fetch_channel is causing the error, not c.send. You shouldn't be fetching channels either, and you don't call return

pliant gulch
#

It won't error but it'll return an empty tuple

fading marlin
#

code doesn't match error

supple ridge
#

is there a way by one can limit as to how much a bot has ran?
for example i have a bot abc which sends counting 0-150 now i want the bot to stop when it hits 150 and never run for 24 hours after that it will start from 0 again

frosty umbra
#

Erm

#

you’d need another program to run the bot every 24hours

slate swan
#

i mean you can stop the bot once its hits the count limit but starting it back up wont have anything to do with the bot itself

supple ridge
frosty umbra
#

Just stop the bot when it hits 150

#

quit()

supple ridge
#

thats what i wish to do

#

something like sorry you hit 150 etc etc

frosty umbra
#

Can you just do a wait for 24 hours

#

And have only you run the bot

slate swan
#

how are u gonna show an error if the bot isnt even running

frosty umbra
supple ridge
#

ye

slate swan
#

he still can't he stopped the bot lmao

frosty umbra
#

He wpuld need a second program running

#

To detect when the bot has stopped running

supple ridge
#

o okayokay

frosty umbra
#

Basicslly

#

No dont do this kekw

slate swan
#

yea lmao

supple ridge
#

okay

frosty umbra
#

Just quit the bot after 150 and then restart it in 24 hours

slate swan
#

or just "disable" the counting function so you can still respond with the bot if someone tries to "start" it again

supple ridge
#

okok

#

also is there a way i can write something to a file when i manually close the program by pressimg the cross button

frosty umbra
#

There is no different between manually closing and closing with a script a think

#

Unless you go binary level LOL

frosty umbra
#

You could try to detect if the mouse is hovering over the cross button

#

But that would be difficult

supple ridge
#

damn okay

frosty umbra
#

You could make a command to start the counting and leave it running 24/7

#

And make it have a cooldown of 24 hours

supple ridge
#

hmmm

#

okay I'll see thanks

frosty umbra
#

And make it so only you can run it

white citrus
red ferry
#

import os


client = discord.Client(intents=discord.Intents.all())


@client.event
async def on_ready():
        print('Bot is online, as {0,user}'.format(client))

@client.event

async def on_message(message):
        if message.author == client.user:
                return
        if message.content.startswith("$Hello"):
                await message.channel.send("Hello!")

client.run(os.getenv("token"))

#
  File "main.py", line 21, in <module>
    client.run(os.getenv("token"))
  File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start
    await self.login(token)
  File "/home/runner/WoefulOutrageousProjections/venv/lib/python3.8/site-packages/discord/client.py", line 577, in login
    raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead
 ```
#

This is the error i get

supple ridge
#

i think i found a way, what i can do is first of all making my code exit by keyboardintterupt
catch the keyboard intterupt and write the value of counting in a file
then when the bot is restarted use that value and update it again on exit

shrewd gorge
#

can you make a bot stream in vide channels

regal cove
#
    await ctx.response.send_message((embed=em), ephemeral = False)
``` i get syntax error on the embed=em part
#

why does this happen?

cedar fulcrum
#

I mean what library

#

Oj dpu

regal cove
#

i fixed it thank you

#

i noticed that myself after checking again lol

cedar fulcrum
regal cove
#
@client.event
async def on_message(message):
  if message.author.client:
    return
  File "/home/runner/level-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 32, in on_message
    if message.author.client:
AttributeError: 'Member' object has no attribute 'client'``` help pls
regal cove
#

in what way should i do that?

slate swan
#

message.author refers to member, user

#

and member.bot is the bot.

#

so its message.author.bot

primal token
slate swan
primal token
slate swan
#

yeaa i dont they even understand what we are talking ab anyways. member.client

#

lol

#

nobody reads docs anymroe

primal token
#

Guess i dont exist😔

slate swan
#

probably lmfao

regal cove
thick pike
#
from discord.ext import commands
from datetime import datetime, timedelta, timezone

bot = commands.Bot(command_prefix='!')

@bot.command()
async def time(ctx, country: str):
    # Set the timezone for the country
    if country.lower() == 'usa':
        tz = timezone.utc
    elif country.lower() == 'japan':
        tz = timezone(timedelta(hours=9))
    else:
        # If the country is not USA or Japan, use UTC as the default timezone
        tz = timezone.utc

    # Get the current time in the specified timezone
    now = datetime.now(tz)
    current_time = now.strftime('%H:%M:%S')

    # Send the current time to the user
    await ctx.send(f'The current time in {country} is {current_time}')


bot.run('Token')```
#

really simple idk why its not working

bold surge
#

is there any way to pause invites through a bot? I'm using nextcord btw

thick pike
#

no errors just nothing happens

bold surge
#

alright, thanks!

slate swan
#

LMAO jk nextcord is way behind for some reason

#

!d nextcord.Guild.edit

unkempt canyonBOT
#
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., region=..., afk_channel=..., owner=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the guild.

You must have the [`manage_guild`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Permissions.manage_guild "nextcord.Permissions.manage_guild") permission to edit the guild.

Changed in version 1.4: The `rules_channel` and `public_updates_channel` keyword-only parameters were added.

Changed in version 2.0: The `discovery_splash` and `community` keyword-only parameters were added.

Changed in version 2.0: The newly updated guild is returned...
slate swan
#

unfortunate. but in dpy and disnake. its guild.edit(invites_disabled=Bool)

#

it doesn't exist in nextcord. kind of cringe

#

Hm its still not there

slate swan
#

i think thats cuz they are focused on the rewrite rn 🤺, and the feature isn't forsure unnoticed by the devs because they added it in Guild featues

bold surge
#

ill just annoy the owner until they add it

slate swan
#

!d discord.Guild.features

unkempt canyonBOT
#

A list of features that the guild has. The features that a guild can have are subject to arbitrary change by Discord.

They are currently as follows:

slate swan
#

lmfao

pliant gulch
#

Seeing the word "re-write" has given me flashbacks to Rin

#

I think I've rewritten at least 4 times

slate swan
#

is that the case for you?

pliant gulch
#

I have commitment issues

slate swan
#

😏 commit all at once then

pliant gulch
#

Maybe I will

#

Maybe I won't

#

You'll never know... unless

slate swan
#

unless i torture you into doing it

pliant gulch
#

I might actually re-write

#

You got me feeling that kind of way sarth

#

I'm gonna look like an idiot when 5 hours pass and I give up already

slate swan
#

well take your time 🤺 takes another year

pliant gulch
#

It looks oddly familiar 👁️ 👁️

slate swan
#

no wait wtf rin has listeners too

pliant gulch
#

and collectors

#

😏

slate swan
slate swan
#

lemme check

pliant gulch
#
from __future__ import annotations

import asyncio
import os
from datetime import timedelta

import rin

token: str = os.environ["DISCORD_TOKEN"]
intents = rin.IntentsBuilder.default(guild_members=True)
client = rin.GatewayClient(token, intents=intents)


@client.once(rin.Events.READY)
async def ready(user: rin.User) -> None:
    print(f"Logged in as: {user.snowflake}")


@client.collect(rin.Events.GUILD_MEMBER_ADD, timeout=timedelta(seconds=1), amount=5)
async def anti_raid(members: list[rin.Member]) -> None:
    print("Woah! 5 members joined all in 1 second.")
    print("Preparing to ban them just incase of something fishy.")

    asyncio.gather(*(member.ban() for member in members))


asyncio.run(client.start())
#

Wait are your event handlers singleton or bound to a client

slate swan
#

nah i dont anything like that

#

the max_trigger is barely just an attribute that counts event dispatches and disables the listener on exceeding it

pliant gulch
#

very cool if your using @Event.SOMETHING

slate swan
pliant gulch
#

Well with discord.py you have strings so you also don't get auto complete sometimes

slate swan
#

i was earlier planning to use event classes instead of enum and argument based events

@bot.listen(wyvern.MessageCreate)
async def msg_event(event: wyvern.MessageCreate):
   ...
``` structure of which would be similar to the payload the Gateway provides for the particular event
#

thats exactly what hikari does

#

so i ditched it ;-;

pliant gulch
#

I use that too

#

I think, if I am understanding you correctly

slate swan
#

Ooo i understand now after looking at the source code 🛐

pliant gulch
#

I think Im gonna go for a state style wrapper ```py
async def main() -> None:
token = environ["DISCORD_TOKEN"]
intents = (
Intents.GUILD_MEMBERS |
Intents.GUILD_MESSAGES |
Intents.GUILD_PRESENCES
)

async with GatewayClient(token, intents) as client:

    @client.messages.create()
    async def message(message: Message) -> None:
        print(message)

    @client.channels.delete()
    async def delete_channel(channel: Channel) -> None:
        print(channel)

    print(client.messages.get(123))
    print(await client.messages.fetch(123)

asyncio.run(main())

#

I'll need to do meta-class shenanigans to get event-sub

slate swan
#

basically state class per-object with get, fetch and find methods

slate swan
pliant gulch
slate swan
#

cache dependent i mean

pliant gulch
#

Cache dependent on state?

slate swan
#

like does channel..create callback get triggered only when a channel is added to the cache or based on events?

pliant gulch
#

Event, which then get''s cached then called

slate swan
#

oh that makes sense

#

i tried to implement an internal command handler for slash commands and ended up with duplicate objects

pliant gulch
#

Why haven't I thought about doing this before

somber sky
#

how would I make it where, when u run a command it tells you which role you have? Like pretty much every person has one of those roles. How do I make it say which one out of those roles you have

somber sky
#

what is wrong

slate swan
#

everything, don't use that library anyloner. its unmaintained

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
somber sky
slate swan
#

use discord.py's app_commands, there's a guide for it in the pins

upbeat gust
#

Dont use that library

sick birch
#

we're workin on it

#

🗑️

slate swan
#

ooo oki!

pliant gulch
#

Might change to messages.post since POST PUT PATCH

wicked atlas
#

Except with a context manager

sick birch
wary obsidian
#

Hey guys! Since Heroku free is no longer available, are there any good alternatives?

sand quiver
#

lava link

#

i think is free

wary obsidian
#

Does it have databases?

sand quiver
#

i just looked it up hol up a sec

wary obsidian
#

I saw Fly.io but haven't tried it yet

#

Which apparently also has databases

#

Lost my bot to the shutdown of the free heroku plan

sand quiver
#

nah

slate swan
sand quiver
#

lavalink is for music 😭

wary obsidian
#

🥲

sand quiver
#

i need help though for a code, like it wont play anything in my discord now

sand quiver
#

im trying to play music in my bot but it wont play anymore

sick birch
#

that's the thing, there's nothing related to it on the API

#

it's basically an unannounced breaking API change

#

and it's fucking with our bots

slate swan
#

average discord api moment

sand quiver
#

i enabled for it to speak and connect but it just wont do that

sick birch
#

like seriously

#

breaking fucking api change and it's unannounced ?!?!?

sand quiver
#

like it'll connect ot your vc and even add to the queue but wont play nothing you tell it to play

sick birch
#

we seem to have come up with a solution but pushing to get discord.py to patch it

#

hence the issue

sand quiver
#

lol

slate swan
#

monkeypatch the library lol

pliant gulch
#

Is pydis gonna use a git commit as the source?

sand quiver
#

fuck i forgot what level i need to talk in vc for

pliant gulch
#

Cause I don't think discord.py is gonna do a hot fix to pypi

#

Or maybe they will

pliant gulch
#

I know what your talking about but I don't actually know the name for that design pattern or whatever you call it

#
let foo = Foo()
    .bar(...)
    .baz(...)
feral timber
#

Hello humans of #discord-bots!

At about 0040 UTC, Discord released a breaking change to their API, which causes bots to fail to react with any non-default emojis with this error:

400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "incident_actioned" is not snowflake.

As far as we know, Discord has not posted any notice about this change. There doesn't appear to be any notice in the change-log either.

Stripping the leading : from your emojis seems to fix this issue. See Rapptz/discord.py#9116 for more details.

sick birch
#

thanks doggo

sand quiver
#
    @commands.guild_only()
    async def play(self, ctx, *, url):
        """Plays audio hosted at <url> (or performs a search for <url> and plays the first result)."""
        client = ctx.guild.voice_client
        state = self.get_state(ctx.guild)  # get the guild's state

        await ctx.send('Hold on. lemme go get it')

        if client and client.channel:
            try:
                video = Video(url, ctx.author)
            except youtube_dl.DownloadError as e:
                logging.warning(f"Error downloading video: {e}")
                await ctx.send(
                    "There was an error getting your video, sorry.")
                return
            state.playlist.append(video)
            message = await ctx.send(
                "Added to queue.", embed=video.get_embed())
            await self._add_reaction_controls(message)
        else:
            if ctx.author.voice is not None and ctx.author.voice.channel is not None:
                channel = ctx.author.voice.channel
                try:
                    video = Video(url, ctx.author)
                except youtube_dl.DownloadError as e:
                    await ctx.send(
                        "There was an error getting your video, sorry.")
                    return
                client = await channel.connect()
                self._play_song(client, state, video)
                message = await ctx.send("", embed=video.get_embed())
                await self._add_reaction_controls(message)
                logging.info(f"Now playing '{video.title}'")
            else:
                raise commands.CommandError(
                    "You need to be in a voice channel to do that.")```
sick birch
sand quiver
#

bro..

fading marlin
#

Robin! care to give me a few ideas for a project?

sick birch
fading marlin
#

an extension for them, yup. It's a debug/test ext

#

I've kinda ran out of ideas on what to do/add, and I'm looking for some inspiration

sick birch
#

An issue completely unrelated to the aforementioned emoji bug:

@bot.event
async def on_message(message: discord.Message) -> None:
    message._add_reaction = custom_add_reaction
    await bot.process_commands(message)

how does one overwrite and existing discord.py method with a custom one?

Traceback (most recent call last):
  File "/home/robin/Desktop/Coding/emoji-discordpy-test/.venv/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/home/robin/Desktop/Coding/emoji-discordpy-test/main.py", line 15, in on_message
    message._add_reaction = custom_add_reaction
AttributeError: 'Message' object attribute '_add_reaction' is read-only
sick birch
fading marlin
sick birch
#

fuck

fading marlin
slate swan
#

subclass the message class 😏 ```py
class MyMessageStfuDiscordpy(Message):
def init(self, original: Message):
self = original

def add_reaction...

#

not cursed

sick birch
#

i could but i need to alter the internals somehow

#

discord.py would still give me a discord.Message object

slate swan
#

throw it inside the class above, it takes message in its init and changes self to that instance

fading marlin
#

you could keep track of the message's ID and link it with the custom class through a botvar 🤷

sick birch
#

And this shouldn't break anything?

wicked atlas
#

but with the Message class

slate swan
sick birch
#

well yeah but its a temporary monkeypatch

slate swan
#

oo wait f

unkempt canyonBOT
#

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

[No output]
slate swan
#

i see

#

@sick birch shouldn't it work then?

fading marlin
#

__slots__ should only include methods right?

unkempt canyonBOT
#

discord/message.py lines 1531 to 1540

def _try_patch(self, data, key, transform=None) -> None:
    try:
        value = data[key]
    except KeyError:
        pass
    else:
        if transform is None:
            setattr(self, key, value)
        else:
            setattr(self, key, transform(value))```
slate swan
fading marlin
#

ah, icic

slate swan
#

so basically py Message._add_reactions can be overrided
but ```py
<some.message.instance>._add_reactions

#

My friend needs a dc bot so, not that busy with that. Xd i am busy with my exams :[

short pulsar
#

How to make roblox ranking bot 💀💀

#

So

sick birch
#

Another question - how do I access the MessagePayload from an existing discord.Message object?

#

Doesn't seem like it's bound to the instance

slate swan
#

discord.py doesn't provide any way to extract the raw data from objects

#

if you really need it you can get it it from raw_socket_recieve event

#

!d discord.on_raw_socket_recieve

unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
slate swan
#
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 328, in adduser
    await cursor.execute('UPDATE users SET id = ? WHERE ad = ? AND guild = ? AND channel = ?', (member.id, '' ,ctx.guild.id, '',))
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
    return await future
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
    result = function()
sqlite3.OperationalError: no such column: channel

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

Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: channel
#

how can I update the db when I add a new value?

dull horizon
#
async def randomkick(ctx , *, member: discord.User, reason=None, message: discord.Member): 
  member = discord.User(360933425361715200)
  if rand.randint(1, 20) == 1:        
      await ctx.send(format("Cya later " + message.author.mention))
      await member.kick(member, reason=reason)
  elif rand.randint(1, 20) != 1:
      await ctx.send(format(message.author.mention) + " Roll again")```
Hello, I am making a function that will kick a specific individual when anyone types "!randomkick" . It will print the "Cya later" part when a successful roll is made, but it does not kick the user from the discord server.
#
``` is the error
scarlet echo
#

is talking about selfbots not allowed?

slate swan
#

sh

dull horizon
slate swan
#

wait im pulling it up

scarlet echo
#

send my boy them docs

slate swan
#

@dull horizon can u read the py docs

slate swan
wicked atlas
slate swan
#

thought it was discord.Member

#

hmmm

wicked atlas
#

yeah, and I'd use discord.Member as well

sick birch
#

ill see what i can do with this

gusty flax
sick birch
#

mmhm

gusty flax
#

I wish I knew abt that a month ago 😅

sick birch
#

this is gonna get too messy

#

not worth it

#

gonna hope our issue is looked into

#

or discord rolls it back

slate swan
#

use wyvern it givs raw payloads

gusty flax
sick birch
#

!docs

unkempt canyonBOT
#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
sick birch
#

they basically broke emojis

gusty flax
#

Oh that error we keep getting.

#

Are u in charge of fixing it? @sick birch

sick birch
#

no but we made an issue

#

i came up with a solution, it's pretty simple but it works

#

tested it locally

gusty flax
#

Oh it’s a dpy problem?

sick birch
#

no

gusty flax
#

Like discord did smth which caused a problem with dpy right?

sick birch
#

basically

slate swan
#

without a notice lmfao

sick birch
#

I'm getting in contact with discord supports atm

gusty flax
slate swan
#

yes trash cans are bad

gusty flax
#

So that emoji broke? @sick birch

sick birch
#

no

#

custom emojis prefixed with : are broken

#

dropping that seems to fix it

#

our internal mod systems are broken because of that

gusty flax
#

… how did u figure that one out?

gusty flax
sick birch
#

nah

#

other devs on the discord dev server were having the same issue

#

i went in and proposed a change from the internals

unkempt canyonBOT
#

discord/message.py line 125

return emoji.strip('<>')```
sick birch
#

should be changed to return emoji.strip("<:>")

dull horizon
# slate swan ctx.guild.kick(member, reason=reason)

This did not fix it, the issue is that member is a required argument even though it is called.

async def randomkick(ctx, member: discord.Member, message: discord.Member):
  guild = await bot.get_guild(917522331855900705)  
  member = guild.get_member(user_id)
  if rand.randint(1, 20) == 1:        
      await ctx.send(format("Cya later " + message.author.mention))
      await ctx.guild.kick(member,reason='None')```
```discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
gusty flax
slate swan
#

member and message?

dull horizon
#

I need message for
message.author.mention

slate swan
#

no

#

whats it for

#

to mention the author of the message?

dull horizon
#

pings the user

slate swan
#

yea why are there two

wicked atlas
slate swan
#

^

sick birch
#

sumbitted report to discord

dull horizon
sick birch
#

now we wait

slate swan
#

?

#

what report

sick birch
#

dev support

wicked atlas
sick birch
pliant gulch
#

A lot

#

I'll try one

#

Not sure if you want to push possible seg faulting code to main though

slate swan
#

*one that is understandable by others

sick birch
wicked atlas
wicked atlas
pliant gulch
#

Okay lol I think it worked

#

No seg-fault

wicked atlas
sick birch
#

does this actually work 👀

pliant gulch
#

As I say that it seg-faults on message_create

#

Oh, because I didn't impl a dunder?

sick birch
#

omg

#

that actually worked lol

dull horizon
# wicked atlas Nope, just `member.mention()`. You're getting the member you want to mention fro...

I get what you mean, fixed that part. This last line is giving me and error now for some reason

async def randomkick(ctx, member: discord.Member, message: discord.Member):
  guild = await bot.get_guild(917522331855900705)
  print("Message 3")  
  member = guild.get_member(user_id)
  if rand.randint(1, 20) == 1:        
      await ctx.send(format("Cya later " + member.mention())
      await ctx.guild.kick(member, reason='None')```
wicked atlas
#

What error?

#

Ah, I'd say it's because of that unclosed parenthesies

dull horizon
#

nevermind that line was syntax

#

yep

wicked atlas
#

I don't think you need format() ther

slate swan
#

and just use f string

#
@bot.command()
async def randomkick(ctx, member: discord.Member, message: discord.Member):
  guild = await bot.get_guild(917522331855900705)
  print("Message 3")  
  member = guild.get_member(user_id)
  if rand.randint(1, 20) == 1:        
      await ctx.send(f"Cya later {member.mention}")
      await ctx.guild.kick(member, reason='None')
dull horizon
#

Yep have all that but i dont get this discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.

wicked atlas
#

What arguments are you passing to the command?

#

!randomkick @Member?

dull horizon
#

yes

slate swan
#

u dont kick member id

#

i think

#

atleast I dont and it works

wicked atlas
# dull horizon yes

Try removing the message argument, since it looks like you don't need that

slate swan
#

a random kick command that kicks only one user out of all, yes

wicked atlas
#

oh hmmmm

pliant gulch
#

I should've looked back earlier to not waste time

#
from __future__ import annotations

from ctypes import POINTER, py_object, pythonapi
from os import environ

import discord

pythonapi._PyObject_GetDictPtr.restype = POINTER(py_object)
pythonapi._PyObject_GetDictPtr.argtypes = [py_object]

intents = discord.Intents.default()
intents.members = True
intents.message_content = True

original = discord.Message._add_reaction


def patch() -> None:
    mapping = pythonapi._PyObject_GetDictPtr(discord.Message).contents.value
    mapping["_add_reaction"] = lambda self, *args, **kwargs: print("patched")

def unpatch() -> None:
    mapping = pythonapi._PyObject_GetDictPtr(discord.Message).contents.value
    mapping["_add_reaction"] = original


client = discord.Client(intents=intents)
patch()

@client.event
async def on_message(message: discord.Message) -> None:
    message._add_reaction()

client.run(environ["DISCORD_TOKEN"])
sick birch
#

i'll pass it on

wicked atlas
dull horizon
#

i already defined the ! prefix it works for other functions in my program, just not this one

wicked atlas
#

Are you giving it the argument?

dull horizon
# wicked atlas Are you giving it the argument?
from discord.ext import commands
import time
import asyncio
import random as rand
import os
intents = discord.Intents.all()
intents.messages = True
bot = commands.Bot(intents=intents, command_prefix='!')
user_id = 360933425361715200
@commands.has_permissions(kick_members=True)
def getToken() -> str:
    token = open('token.txt','r').read()
    return token
token = getToken()
@bot.event
async def on_ready():
  print(f"We have logged in as {bot.user}")
@bot.command()
async def randomkick(ctx, member: discord.Member):
  guild = await bot.get_guild(917522331855900705)
  print("Message 3")  
  member = guild.get_member(user_id)
  if rand.randint(1, 20) == 1:        
   await ctx.send(f"Cya later {member.mention}")      
   await ctx.guild.kick(member, reason='None')
  elif rand.randint(1, 20) != 1:
      await ctx.send(format({ctx.author} + " Roll again"))
bot.run(token)```
This is what i have im not sure what you mean
wicked atlas
#

Otherwise it would make sense that it says the argument is missing, because you never gave it

dull horizon
#

Just tried i have tested it by pinging someone and now its this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression

wicked atlas
#

get_guild is not async, you don't need to await it

graceful turtle
#

cant you just do ctx.guild ? or is it set for a certain server

dull horizon
graceful turtle
graceful turtle
# dull horizon here
from random import randint

@bot.command()
async def randomkick(ctx, member: discord.Member):
    if randint(1, 20) == 1:
        await ctx.send(f"Cya later {member.mention}")

        return await ctx.guild.kick(member, reason='None')

    await ctx.send(format({ctx.author} + " Roll again"))
#

try this

dull horizon
graceful turtle
dull horizon
graceful turtle
#

the code you sent generates a random number from 1 - 20 and if the number is 1 it will kick the mentioned user

dull horizon
dull horizon
#

only kick if they roll 1

graceful turtle
#

what

#

thats what it did...

#

are you even reading docs or trying to do it right? half of the stuff wasn't even correct

dull horizon
graceful turtle
#

mate

#

wait for someone else lol

#

i gave you exactly what you asked for and you said it was wrong, then explained the same exact thing i had just edited over

dull horizon
graceful turtle
#

not sure what you're asking here man

dull horizon
dull horizon
#

could i do something like

    if randint(1, 20) == 1:
        await ctx.send(f'Cya later {member.mention}')

        return await ctx.guild.kick(member,reason='None')

    await ctx.send(f'Please roll again {ctx.author.mention}!')```
graceful turtle
#

what is ctx.guild.kick mate

dull horizon
#

its what you've sent me before

graceful turtle
#

😂

dull horizon
#

should i use

return await member.kick()```
graceful turtle
#

go read docs

#

you won't learn from asking for help with every simple thing

dull horizon
graceful turtle
rare echo
#

what in the world did i just stumble into

graceful turtle
rare echo
vale wing
#

Why do this

if cond1 == "a":
    if cond2 == "b":
                ...

When you can

if cond1 == "a" and cond2 == "b"```
unkempt canyonBOT
#
all

all(iterable)```
Return `True` if all elements of the *iterable* are true (or if the iterable is empty). Equivalent to:

```py
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
shrewd apex
#

lmao

drifting arrow
#

How do I make a discord bot remember buttons it is connected to?

drifting arrow
#

This way if any of them are wrong it errors out etc.

drifting arrow
#

I want the buttons to work if the bot goes offline for a moment

unkempt canyonBOT
#

examples/views/persistent.py lines 39 to 45

async def setup_hook(self) -> None:
    # Register the persistent view for listening here.
    # Note that this does not send the view to any message.
    # In order to do this you need to first send a message with the View, which is shown below.
    # If you have the message_id you can also pass it as a keyword argument, but for this example
    # we don't have one.
    self.add_view(PersistentView())```
naive briar
#

Make it persistent

drifting arrow
kind trellis
#
    @commands.command(name='edit-specific', hidden=True)
    @commands.is_owner()
    async def _edit_specific(self, ctx, type = None):
        if type == 'role-request':
            message = await ctx.fetch_message(1038828402536349736)
            embed = message.embeds[0].fields[0].value = '''
The following roles can be requested:
- <@&762321175900454933>
- <@&763478824641495040>
- <@&959865461846204436>
- <@&853817144243650561>
- <@&1024429857104478228>
- <@&1045827799967088840>
            '''
            embed = message.embeds[0].footer.text = f'Developed by {self.bot.owner}'
            await message.edit(embed=embed)

The traceback says that await message.edit(embed=embed) is throwing an AttributeError where 'str' object has no attribute 'to_dict'

glad cradle
#

😭

pulsar bridge
#

How'd I invoke a command without context from within an event handler?
E.g. If I was running it from an on_guild_join event or on_ready

slate swan
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
slate swan
#

!d discord.ext.commands.Command.callback

unkempt canyonBOT
#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
pulsar bridge
#

I'll try it... but knowing myself I'm not gonna make it work

#

Actually, @slate swan
I'll rephrase my question cause I may have left out some needed information

I'm trying to get a tasks.loop to start whenever the on_ready event is activated.
How'd I go about doing so?

#

Nevermind. I'm an absolute idiot

#

I apologize for the waste of time

vale wing
vale wing
shrewd apex
shrewd apex
shrewd apex
slate swan
#

oh asher already pointed that

pulsar bridge
#

What if they aren't in a COG?

Now I'm trying to invoke a command from a tasks.loop

#

I'm unsure of what I'm supposed to do with the callback you mentioned earlier

slate swan
#

what else would you do with a callback

shrewd apex
#

i dont think u can call the callback/command from a task coz u won't be able to get the first positional

slate swan
#

Pass anything there as long as you're not using ctx inside the callback

pulsar bridge
slate swan
#

if the command requires a context, its stupid to call one from a loop

slate swan
pulsar bridge
#

I could, but that might create more problems

#

Seems like it's the only solution though, at least until I get good enough to try and figure something out lol.
Thanks, Sarth, Asher, for the help!

slate swan
#

if you are able to tell what you're actually trying to do, we might be able to find easier solutions.

pulsar bridge
#

Right right

#

Task loop that runs every second, counting down a timer logged in a database, after the timer hits 0, it runs an external command that sends an embed and changes things to the database

#

Need more detail?

slate swan
#

so all that the command does is send an image in a specific channel right?

#

and the db changes

#

no data like a command invocation is required

slate swan
#

!d discord test emoji

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

#

Sorry, an unexpected error occurred. Please let us know!

In emoji_id: Value "trashcan" is not snowflake.```
slate swan
#

it doesn't work for some reasons

slate swan
pulsar bridge
slate swan
#

bro

shrewd apex
slate swan
#

Nope, 2.0.1

slate swan
#

formatting*

#

thats exactly the issue here

slate swan
limber bison
#

How can I make this condition true ([1,2] == [2,1])

shrewd apex
#

set()

slate swan
unkempt canyonBOT
#

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

True
shrewd apex
#

lmao

limber bison
#

Ohh ok

#

Thanks 👍

shrewd apex
#

when typing speed maxes out on phone

slate swan
#

or you could do sorted on both lists but thats overkill

limber bison
#

#bot-commands

slate swan
limber bison
#

Is there any sub set concept in python ?

#

If A is sub set of b -> true

#

Like this

shrewd apex
#

!e

print (dir(set))
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.

['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
shrewd apex
#

subset is also there apparently

slate swan
#

!e print({1,2}&{1})

#

bitwise ops

#

but that checks only if an intersection exists hmm

#

you can use < to check proper subsets and <= to check subsets

limber bison
#

Got it thanks buddy

#

It means alot

surreal sierra
#

hi, just came back to coding a bit and seems like some commands on my old bot doesnt work anymore.

It gives an error on line 209

slate swan
#

the error is coming from update_bank function

#

and pls don't use json as a database

surreal sierra
#

I know u are not supposed to use json as databases but this is from when I first started coding with this bot.
I will move on to sqlite later and try to learn it

slate swan
#

cool!

#

as for your current error you're trying to write in a file where you don't have write permission
are you using w mode or not?

surreal sierra
#

yea, Im using wmode

slate swan
#

Yo

#

first you have to open file on read mode then use it with edit file with write mode

slate swan
surreal sierra
#

okay thx for the help

polar dawn
#

Hi. I'm trying to let the bot react to a message and I kept getting this error:

Value "test1" is not snowflake.

Here's what I tried:

if ctx.guild.id in allowed_guild_id:
    reactions = [':test1:', ':test2:', ':test3:']
else:
    reactions = ['⬅️', '🚫', '➡️']

msg = await ctx.reply("This is a test message")

for x in reactions:
    await msg.add_reaction(x)
slate swan
polar dawn
tropic estuary
#

anyone can help me with an inventory system and databases?

slate swan
#
@bot.command()
async def welcomechannel(ctx, *, channel: discord.TextChannel):
  sql = ''
  val = ''
  if ctx.author.guild_permissions.manage_messages:
    async with aiosqlite.connect("main.db") as db:
      async with db.cursor() as cursor:
        await cursor.execute(f"SELECT welcomechannel FROM users WHERE guild = {ctx.guild.id}")
        result = await cursor.fetchone()
        if result is None:
          sql = ("INSERT INTO users(guild, welcomechannel), values(?, ?)")
          val = (ctx.guild.id, channel)
          await ctx.send(f"Channel has been set to {channel}")
        elif result is not None:
          sql = ("UPDATE users SET welcomechannel = ? WHERE guild = ?")
          val = (channel, ctx.guild.id)
          await ctx.send(f"Channel has been updated to {channel}")
        await cursor.execute(sql, val)
        await db.commit()
#
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 379, in welcomechannel
    await cursor.execute(sql, val)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
    return await future
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/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 "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.
#

can anyone help me fix this error? (code above)

hushed galleon
#

you cant directly pass a TextChannel object to sqlite, so perhaps you meant to store the channel.id instead

#

@slate swan

white citrus
#

can you select a channel in modals?

hushed galleon
#

afaik its all text inputs right now so not really

lament depotBOT
maiden sonnet
#

Hi
Im creating a discord bot with python but im trying to get a list from a different file. I have a lot of lists in my files and its just becoming a mess.
Is there a way to save the lists in a different file and load them once a command is being used?
Im testing this with a random topic command btw
I dont know much about coding bots but im trying to learn

slate swan
whole sparrow
#

How many times can I edit a message before theres an error? I get a webhook error after a while

#

Im editing the message once every 5 seconds

slate swan
maiden sonnet
#

like how it works and stuff

white citrus
slate swan
#
with open("file.json", "r") as f:
  stuff = json.load(f)
money = stuff[f'{ctx.author.id}']['money']
await ctx.send(money)

#

thats for if you want to load a users stuff

glad cradle
maiden sonnet
maiden sonnet
#

Sorry if im asking dumb questions. Im kinda new to all of this

slate swan
#

@maiden sonnet you could make a list

#
topics = ["1", "2", "3"]

choice = random.choice(topics)
print(choice)
maiden sonnet
#

I know i already have that but i have multiple commands that use a big list so its getting hard to find specific commands

#

so thats why im trying to put it in a different file

slate swan
#

you could make a txt file

hushed galleon
maiden sonnet
hushed galleon
#

same way you would with any other message component, either subclass the ChannelSelect or use the decorator form, although nextcord seems to do it a bit differently

#

probably something like this py class MyView(nextcord.ui.View): @nextcord.ui.channel_select() # documented just below ChannelSelect async def on_select(self, select, interaction): ...

slate swan
#
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 33, in on_ready
    await cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER, ad STRING, guild INTEGER, welcomechannel INTEGER, adchannel INTEGER, welcomemessage STRING, leavemessage STRING, announcechannel INTEGER)')
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
    return await future
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
    result = function()
sqlite3.DatabaseError: database disk image is malformed
#

what does this even mean

white citrus
hushed galleon
#

whatever you want to do? the interaction object gives you the methods for sending back a response, and the select is the ChannelSelect with the .values property that tells you what the user picked

white citrus
upbeat otter
hushed galleon
upbeat otter
#

yes

#

oh sarth 🛐

hushed galleon
white citrus
hushed galleon
#

nextcord.ui.ChannelSelect is just a class, but you need to use an actual instance of that class because that carries the data for you, and the instance is given by your select parameter, so to use it would look something like this: py @nextcord.ui.select(...) async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction): channels = select.values.channels # I don't get why nextcord added an extra ".channels" property, # but that's what the documentation says for channel in channels: print(channel.name)

white citrus
hushed galleon
#

no, you just need to index the first channel from the .channels list

white citrus
hushed galleon
#

they still give it to you as a list, even if its one channel

white citrus
#

Okay so now i can send the view?

#
class select_channels(nextcord.ui.View):
    def __init__(self):
        
        @nextcord.ui.channel_select(channel_types=nextcord.ChannelType.text, max_values=1)
        async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction):
            channels = select.values.channels
            for channel in channels:
                print(channel.name)```


```py
    @nextcord.slash_command(name="global-chat", description="Edit the GlobalChat settings")
    async def global_chat(self, interaction: nextcord.Interaction,
                          option: str = SlashOption(name="option", description="please choosen an option", choices=["activate", "show", "delete"])):
        
        match option:
            case "activate":
                dict_one = {"_id": interaction.guild.id}
                first_check = await interaction.client.settings.find(dict_one)
                
                view = select_channels()
                
                if first_check is not None:
                    if "global_id" in first_check:
                        response = nextcord.Embed(description=f"{config.DiscordError} You already have an active Global Chat. --> <#{int(first_check['global_id'])}>", colour=config.red)
                        await interaction.response.send_message(embed=response)
                        
                    else:
                        await interaction.response.send_message(view=view)
                        data = {"_id": interaction.guild.id, "global_id": "here i want the selection from the view"}
                        await interaction.client.settings.upsert(data)
                
                else:
                    data = {"_id": interaction.guild.id, "global_id": "here i want the selection from the view"}
                    await interaction.client.settings.upsert(data)```

Is it so okay?
#

@hushed galleon

slate swan
#

why don;t you run it and see lol, an error won't hurt

hushed galleon
#

you might want to consider moving those if-statements and upserts into your view callback so you have easier access to the channel values

white citrus
# slate swan why don;t you run it and see lol, an error won't hurt
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 512, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 191, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 906, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\cog.py", line 464, in global_chat
    await interaction.response.send_message(view=view)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 872, in send_message
    payload["components"] = view.to_components()
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 223, in to_components
    children = sorted(self.children, key=key)
AttributeError: 'select_channels' object has no attribute 'children'````
slate swan
#

your indentations are also quite messed up

hushed galleon
#

oh yeah i didnt even notice that init was there

slate swan
#

same

primal token
#

same

white citrus
slate swan
#

same(3)

slate swan
# white citrus Okay so pass it?

no, this is what it should look like py class MyView(ui.View): @ui.channel_select(...) async def select_callback(self, select: ui.Select, inter: Interaction) -> None: ... in case you override the __init__ dunder you'll be calling super().init in order to do stuff that the actual view class does internally

class MyView(ui.View):
    def __init__(self):
        ... #do your stuff
        super().__init__(**kwargs_the_init_takes)

    @ui.channel_select(...) # notice the indentation.
white citrus
# slate swan no, this is what it should look like ```py class MyView(ui.View): @ui.channe...
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 392, in _scheduled_task
    await item.callback(interaction)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py", line 165, in on_select
    channels = select.values.channels
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in channels
    return [v for v in self.data if isinstance(v, GuildChannel)]
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in <listcomp>
    return [v for v in self.data if isinstance(v, GuildChannel)]
NameError: name 'GuildChannel' is not defined```
naive briar
#

Good job

white citrus
slate swan
#

how can I format my member count? to 1st 430th 869th 862nd 1343rd

hushed galleon
slate swan
#

?

#

Wait

#

@hushed galleon it's better u answer xd

#

yh lol

hushed galleon
#

id just use a package like inflect to generate those ordinals for you

#

!pypi inflect

unkempt canyonBOT
#

Correctly generate plurals, singular nouns, ordinals, indefinite articles; convert numbers to words

slate swan
#

english?

#

O.o

hushed galleon
#

1st 2nd 3rd, those are ordinals, someone wrote a package that writes them for you

slate swan
#

So like using this docs...
when a member joins check the current member count and convert the current count to ordinals number with this package and send it

#

# plural plural_noun plural_verb plural_adj singular_noun no num
# compare compare_nouns compare_nouns compare_adjs
# a an
# present_participle
# ordinal number_to_words
# join
# inflect classical gender
# defnoun defverb defadj defa defan
#

number_to_words?

#

Check their docs

#
embed = discord.Embed(description=result1[0] + {format}.format(members=members, mention=mention, user=user, guild=guild, p.members(word)))
hushed galleon
#

that is their docs, they show an exmaple of the ordinal() method below

slate swan
#

hmmm

#

can I do f string?

#

yes

#

alr im testing

slate swan
#
          embed = discord.Embed(description=result1[0] +  p.number_to_words(members).format(members=members, mention=mention, user=user, guild=guild))
          embed.set_author(name=f"{member.name}")
          channel = bot.get_channel(int(result[0]))
          await channel.send(embed=embed)
#

Bro just use f string

#

It looks messy ngl

#

^

#

im using sqlite

#

how's that related here

slate swan
#

@slate swan

#

i was thinking something else

#

Xd

#

but I need help with this to find the right format

#

p.ordinal(position)

#

oh not got it

#

f"{result[0]} {p.ordinal(members}"

#

🌚

slate swan
#

Just use latest one my guy

white citrus
#

I did it today

slate swan
#

do pip list

#

And check the version of nextcord and compare it in their docs latest version

slate swan
unkempt canyonBOT
ebon island
#

Hey there! I'd like to specify:

https://github.com/DisnakeDev/disnake/tree/fix/voice-reconnect-speak

as my branch for disnake in my Requirements. I want the latest version from that branch to be written to requirements.txt such that I can use that to drive my docker-compose build with that specific version. How do I accomplish this? Thanks 🙂

GitHub

An API wrapper for Discord written in Python. Contribute to DisnakeDev/disnake development by creating an account on GitHub.

white citrus
#

@slate swan

thorn python
#

Hey guys

slate swan
#

how do i do the join servers for you auth thing so if the server get's deleted everyone can join back

thorn python
#

I have some doubts about how I can make a slash command trigger another ones

slate swan
steep estuary
#

what are the maximum number of buttons a message can have?

steep estuary
thorn python
#

Can I make it like:

do_your_stuff(info1, info2)
await discord.creatchannel()```
#

Something like this

white citrus
shrewd apex
#

describe is for slash

shrewd apex
thorn python
slate swan
#

anyone got a good oauth2 tutorial

shrewd apex
#

just make a common function which is triggered by both commands instead of using one command to trigger another one which can lead to bugs with interaction responses

leaden linden
#

whats wrong with my code? the bot is online but does not obey to the commands

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

leaden linden
#

where exactly?

#

what about now? still the same problem 😦

ebon island
vital tangle
maiden fable
#

So like you want it so that the latest version from that specific branch is installed when u use a requirements.txt?

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 388, in _scheduled_task
    allow = await self.interaction_check(interaction)
TypeError: 'ChannelSelect' object is not callable```

```py
class select_channels(nextcord.ui.View):
    def __init__(self, ctx_or_interaction):
        super().__init__()
        
        self.ctx_or_interaction = ctx_or_interaction
        if isinstance(ctx_or_interaction, Context):
            self.user = ctx_or_interaction.author
        if isinstance(ctx_or_interaction, Interaction):
            self.user = ctx_or_interaction.user
        
        
    @nextcord.ui.channel_select(channel_types=[nextcord.ChannelType.text], max_values=1)
    async def interaction_check(self, interaction):
            
        if self.user == interaction.user:
            return True
        else:
            await interaction.response.send_message(content="You are not allow to select the channel!")
            
    async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction):
        channels = select.values.channels
        for channel in channels:
            print(channel.name)
            
        data = {"_id": interaction.guild.id, "global_id": channel.id}
        await interaction.client.settings.upsert(data)```
maiden fable
vital tangle
#

i,am starter

maiden fable
#

Hey @ebon island I think I have found a solution to yr problem

#

git+https://github.com/DisnakeDev/disnake@fix/voice-reconnect-speak
Try using this in yr requirements.txt . This will automatically install disnake from that branch directly

proud apex
#

How to prohibit the use of bot commands in private messages with him, but so that some commands can be used?

maiden fable
#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

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

If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
ebon island
unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

naive briar
#

Ah, right

white citrus
maiden fable
naive briar
white citrus
naive briar
#

And why are you making it a channel select

white citrus
#

Because the user should select one channel

#

For the global chat

naive briar
#

Shouldn't you make this one a channel select?

#

That method is unused ducky_sus

white citrus
#

Oh

#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 392, in _scheduled_task
    await item.callback(interaction)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py", line 182, in on_select
    channels = select.values.channels
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in channels
    return [v for v in self.data if isinstance(v, GuildChannel)]
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\select\channel.py", line 58, in <listcomp>
    return [v for v in self.data if isinstance(v, GuildChannel)]
NameError: name 'GuildChannel' is not defined

@naive briar

maiden fable
#

Nice

#

Thank nextcord for that lol

naive briar
#

Try updating your library if you can ducky_regal

slate swan
#

I need some help with sending downloaded files from my pc using a discord (a .jpg)

#

Im quite stuck how to solve the problem

#

Can anyone help me out?

#

what does this have to do with discord bots?

#

my bot sends it

maiden fable
#

!d discord.File is what u need

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.
slate swan
#

Yes im currently working on it

maiden fable
#

Might wanna share it with us

slate swan
#
import discord
import instaloader
import os

class Insta(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @commands.command(description="Sends instagram display picture of an account")
    async def pfp(self, ctx, dp):
        insta = instaloader.Instaloader()
        insta.download_profile(dp, profile_pic_only=True)
        for filename in os.chdir(dp):
            if filename.endswith('.jpg'):
                await ctx.send(file=discord.File(filename))
        
async def setup(bot):
   await bot.add_cog(Insta(bot))   ```
maiden fable
#

Please use the syntax highlighting

#

!code

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
#

the instaloader module makes a seperate directory

#

when you download a photo

#

its outside of my bot directory

#

and i never worked with sending files

#

The photo is getting downloaded

#

but after that idk

#
    def __init__(self, bot):
        self.bot = bot
    @commands.command(description="Sends instagram display picture of an account")
    async def pfp(self, ctx, dp):
        insta = instaloader.Instaloader()
        insta.download_profile(dp, profile_pic_only=True)```
#

this part works

slate swan
#

just do this

photo = insta.download_profile....
#

@slate swan then send/use the photo var

#

could you elaborate on that?

#

just set the downloaded profile to a variable?

#

unless you actaully need to store it for long term use

#

which by looking at the cmd it doesn't seem you do

#
async def pfp(self, ctx, dp):
        insta = instaloader.Instaloader()
        profile = insta.download_profile(dp, profile_pic_only=True)
        .send(file=discord.File(profile)
#

alright

#

let me try

#

I think i have to change directory

#

because the download makes a new folder of that profile name

#

u need to do that in the instaloader class

#
@bot.command()
async def welcomechannel(ctx, channel):
  sql = ''
  val = ''
  try:
    channel = int(channel)
    channel = bot.get_channel(channel)
  except:
    await ctx.send("Channel not found, maybe use the channel ID?")
  else:
    if ctx.author.guild_permissions.manage_messages:
      async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
          await cursor.execute(f"SELECT welcomechannel FROM users WHERE guild = {ctx.guild.id}")
          result = await cursor.fetchone()
          if result is None:
            sql = ("INSERT INTO users(guild, welcomechannel), values(?, ?)")
            val = (ctx.guild.id, channel)
            await ctx.send(f"Channel has been set to {channel}")
          elif result is not None:
            sql = ("UPDATE users SET welcomechannel = ? WHERE guild = ?")
            val = (channel, ctx.guild.id)
            await ctx.send(f"Channel has been updated to {channel}")
          await cursor.execute(sql, val)
          await db.commit()

why is it saying that the channel is found

#

is says not

#

it*

#

also can't u just channel: discord.TextChannel and tag the channel?

#

yea but how can I get id

#

its a channel object

#
ing exception in command welcomechannel
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 369, in welcomechannel
    await cursor.execute(sql, val)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
    return await future
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/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 "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.
#

@slate swan

#
  sql = ''
  val = ''
  channel = channel.id
  channel = bot.get_channel(channel)
  if ctx.author.guild_permissions.manage_messages:
      async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
          await cursor.execute(f"SELECT welcomechannel FROM users WHERE guild = {ctx.guild.id}")
          result = await cursor.fetchone()
          if result is None:
            sql = ("INSERT INTO users(guild, welcomechannel), values(?, ?)")
            val = (ctx.guild.id, channel)
            await ctx.send(f"Channel has been set to {channel}")
          elif result is not None:
            sql = ("UPDATE users SET welcomechannel = ? WHERE guild = ?")
            val = (channel, ctx.guild.id)
            await ctx.send(f"Channel has been updated to {channel}")
          await cursor.execute(sql, val)
          await db.commit()
naive briar
#

Where do you create users table

slate swan
#

await cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER, ad STRING, guild INTEGER, welcomechannel INTEGER, adchannel INTEGER, welcomemessage STRING, leavemessage STRING, announcechannel INTEGER)')

#

ur still passing

#

channel object into the db. you need to pass channel.id

#

oh ok I see

naive briar
#

Right ducky_regal

slate swan
#

also you don't need to get the channel again. you already have the channel object.

#
  channel = channel.id
  channel = bot.get_channel(channel)

this is redundant

sick birch
slate swan
#

discord is actually quite annoying. they also made a change to bots not being able to access the endpoint to change guild vanitys

#

so im trying to get the channel from the db @slate swan any help?

#
          await cursor.execute(f"SELECT announcechannel FROM users WHERE guild = {ctx.guild.id}")
          result = await cursor.fetchone()
          if result is None:
            await ctx.send("You dont have an announcement channel setup.")
          else:
            await result.send_message(message)

#

whats the error?

#
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 382, in announce
    await result.send(message)
AttributeError: 'tuple' object has no attribute 'send'

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

Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'tuple' object has no attribute 'send'
#

also

await cursor.execute(f"SELECT announcechannel FROM users WHERE guild = ?", ctx.guild.id)
#

yh ik

slate swan
#

I can also just do result[0]

#

wanna see sumn cool

#
def field(command, *values):
    cur.execute(command, tuple(values))

    if (fetch := cur.fetchone()) is not None:
        return fetch[0]


def record(command, *values):
    cur.execute(command, tuple(values))

    return cur.fetchone()


def records(command, *values):
    cur.execute(command, tuple(values))

    return cur.fetchall()


def column(command, *values):
    cur.execute(command, tuple(values))

    return [item[0] for item in cur.fetchall()]


def execute(command, *values):
    cur.execute(command, tuple(values))


def multiexec(command, valueset):
    cur.executemany(command, valueset)
#

ayo

#

ion understand shit 🫡

naive briar
slate swan
#
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 378, in announce
    result = await cursor.fetchone[0]
TypeError: 'method' object is not subscriptable

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

Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
slate swan
#

await result[0].send(message)

#

fetchone is a method u still have to call it

#

no

#

fetchone()[0]
or
.send(result[0])

#

im sending a message to the channel

#

im getting the channel from the db

#

ok u should prob go learn some basics if u dont understand what ur doing wrong

naive briar
#

You're getting the id, not the channel object ducky_sus

slate swan
#

result = await cursor.fetchone[0]

#

anything I do its wrong still

#

ur db is storing the channel id right?

#

ur getting the channel id

#

channel obj

#

no ur db doesn't store a channel obj

#

lmao wtf

#

1048657939503792198

#

the id is in there

#

yeah so u need to get the channel obj using that id

#
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 378, in announce
    result = await cursor.fetchone[0]
TypeError: 'method' object is not subscriptable

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

Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not subscriptable
#

again you should go learn some python basics

#

got it

slate swan
#

u dont even listen i alr told u what u was doing wrong lmao

#

yea i was pasting to show cat what u did lmao

slate swan
#

sorry

dull horizon
#

I am making a kick roulette. The conditions are !randomkick @<user> but I only want it to be able kick one specific discord user as dictated by their discord ID.

async def randomkick(ctx, member: discord.Member):
  roulette = rand.randint(1,20)
  if roulette == 1 and member.mention == user_id:
    await ctx.send(f'Cya later {member.mention}')
  
    return await member.kick()

  await ctx.send(f'Please roll again {ctx.author.mention}!')```
This code works but it will allow anyone to mention someone and attempt to kick them
naive briar
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").

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

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.

leaden linden
#

is it possible to make a music bot with python ?

fading marlin
#

sure

leaden linden
#

what is the code needed to make it

fading marlin
#

lavalink, discord API wrapper in python (unless for some reason you wanna make your own), and music?

#

what does result[0] print out? nvm

#

(990210613340934164,) that's a tuple, and the id you want is in it's 0th index

#

you don't have to cast int to it either, since it's already an integer

#

no, that'd still return (990210613340934164,)

#

you access the integer inside the given tuple?

naive briar
#

You should learn to solve some problems on your own sometimes

fading marlin
#

nope

#

you don't even need to use utils.get in this case

#

!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.
timid spade
#

its not getting ready

#

stuck here

naive briar
#

What do you mean

#

It is ready if it says the bot is connected

sick birch
timid spade
fading marlin
#

how is it not working?

thorn python
#
async def create_channels(ctx):
    for name in _list:
        await Guild.create_role(name=name)```

This keeps raising `discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: create_role() missing 1 required positional argument: 'self'`
#

Why?

naive briar
#

Ok

fading marlin
#

you need an instance, not the class

thorn python
#

Explain more, please

fading marlin
#

Guild is a class. create_role is a method of an instance of Guild. You can't "merge" them

thorn python
#

And how do I solve it?

sick birch
#

You just told it, "make this role in a server"