#discord-bots

1 messages · Page 98 of 1

rare echo
#

it’s not a you issue trust me

vital echo
#

i use nextcord, so i dont have an discord.py package

rare echo
rare echo
#

isn’t their whole thing replacing discord with nextcord

naive briar
slate swan
rare echo
granite sun
#

Hello, good morning, guys, I'm not sure how I can handle this, I'm new to python and I'm coming from JS

['1\n7\n9\n21\n8\n14\n7\n21\n24\n1\n2\n31\n19']

I'm trying to use split.. text.split('\n/g'))

rugged shadow
#

Removing that /g should fix it, because currently it's splitting based on the literal "\n/g" delimiter

granite sun
rugged shadow
#

No problem <3

cloud dawn
rugged shadow
#

They did not specify that they were using the re module

cloud dawn
#

!d re.split

unkempt canyonBOT
#

re.split(pattern, string, maxsplit=0, flags=0)```
Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list.

```py
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
rugged shadow
#

I guess that helps too, though

cloud dawn
#

@granite sun

pliant gulch
#
In [2]: %timeit -n10000000 '1\n7\n9\n21\n8\n14\n7\n21\n24\n1\n2\n31\n19'.split("\n")
211 ns ± 1.47 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

In [3]: %timeit -n10000000 re.split(r"\n", '1\n7\n9\n21\n8\n14\n7\n21\n24\n1\n2\n31\n19')
866 ns ± 15.4 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
``` and by a lot too
pulsar solstice
#
@bot.event
async def on_message(message):
    handle = await aiofiles.open(f'{message.guild.id}.txt', mode='r')
    data = await handle.read()
    if str(message) in data:
        await message.delete()
        handle.close()```
#

why is this not working?

#

I have the word "cheese" in the txt file

#

but It still doesn't wor

unkempt canyonBOT
feral frost
#

where can i find the discord_component lib ?

light violet
#
async with aiohttp.ClientSession(headers=headers, connector=None) as session:
    async with session.patch(f"https://discord.com/api/v10/guilds/{ctx.guild.id}/",json={"name" : "test"} ) as r: ```
#

Getting error of 404 not found

#

Help

feral frost
#

anyone knows how i can do a simple 1+1 task with buttons ?

#

pls help me 🙂

light violet
#

Send code

feral frost
#

?

light violet
#

On button callback

feral frost
#

what ?

#

bro i have no code i am asking for help with code

light violet
#

....

feral frost
#

and why you friend request me

light violet
#

@feral frost just wanted to increase frnds

feral frost
#

ok

#

help me and i will be your friend

sick birch
feral frost
sick birch
#

🤔

#

You subclass view, create 3 buttons, and store the currently clicked button's state and bind it to the view subclass. And on each button click, depending on the state, you send 1+1=2 or update bound state

slate swan
#

a calculator you mean

feral frost
sick birch
feral frost
#

ye but like how

#

how do i subclass view and how do i store it

sick birch
#

How... what? I just gave you instructions

sick birch
feral frost
#

ok ty

slate swan
# feral frost yes but i wanna begin simple

what robin said and maintain a string with the operation to perform
like a base string ```py
base = ""

on 1 clicked

base+= "1"

on + clicked

base+="+"

on 1 clicked again

base+="1"

#

theres better ways but this is the easiest i could think of

feral frost
#

ah ok

feral frost
slate swan
#

!d ast.literal_eval

unkempt canyonBOT
#

ast.literal_eval(node_or_string)```
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, `None` and `Ellipsis`.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
feral frost
feral frost
naive briar
#

Sad

#

Just call it with the operation you want to execute

feral frost
#

ok

indigo pilot
slate swan
indigo pilot
indigo pilot
#

Clearly it is, because it works on my other bots thats running a older version

#

so guessing it is with the new push, and if i lower the version it will work lol

slate swan
#

smh arguing with people is like arguing with fools walls

indigo pilot
#

not trying to aruge, just stating the obious /shrug

slate swan
#

obvious*
and right, I'll just step back

indigo pilot
#

withs with 9 and 11

sick birch
mighty pilot
#

Anybody know how I can make my bot post something once every 24 hours? I currently have it written to post a fact when someone uses -fact but I'd like that to happen on its own once every day.

Someone suggested using cron but that would just start the bot not prompt the bot to post something. Unless I made it so it posts on ready and stops the bot afterwards

cold sonnet
#

use a task

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
cold sonnet
#

also

#

that's the best goddamn name I've seen on discord yet

mighty pilot
#

Mine? Lol

cold sonnet
#

yes

mighty pilot
#

I've had this username on all platforms since I started an Xbox 360 account lol

#

Idk 15? Years ago

shut tendon
#

Hey guys I created a mute command, but i don't know how to add the "mute" role to all text channels

cold sonnet
mighty pilot
# cold sonnet I'm that old

I had to think on it for a minute. 15 sounded like a lot of years for something as recent as the Xbox 360 but I just Googled and it came out in 05 so 15 is probably close Norow

honest shoal
shut tendon
#

Yeah that works

#

But i don't know what to do, to add the "mute" commands to all channels

#

I've been looking the docs and tried to use Textchannel set permissions

honest shoal
shut tendon
#

mmm imma look into it

honest shoal
#

bot can again overwrite the permissions for text channels

#

but it's a bad practice

shut tendon
#

no

#

it's not that, cuz i did the exactly same thing by hand without the bot

#

and it's the same, so you must add that muted role and set it on text-channels too

drifting arrow
#

Using discord webhooks, is it possible to tag someone or role?

glad cradle
#

are u using discordpy?

drifting arrow
#

Just put the id betwee <@ >

#

for example: @drifting arrow

sick birch
drifting arrow
#

in discordpy. never had to think about it

unkempt canyonBOT
#

discord/user.py lines 246 to 249

@property
def mention(self) -> str:
    """:class:`​str`​: Returns a string that allows you to mention the given user."""
    return f'<@{self.id}>'```
shut tendon
#

Anyone knows how to remove send_messages in Text_channel for a specific rol?

limber bison
#

i want to create a role check how can i crate ?

my try

def check3(m):
            role = m.guild.get_role(m.content)
            return role in m.guild.guild_roles```
faint sapphire
#

who uses oracle cloud

unkempt canyonBOT
#

await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., display_icon=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") for the guild.

All fields are optional.

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

Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.

New in version 2.0: The `display_icon` keyword-only parameter was added...
limber bison
faint sapphire
faint sapphire
#

bruh

limber bison
#

it will be a string input

faint sapphire
# limber bison it will be a string input
def check(m):
return m.content and m.channel == channel and discord.utils.get(m.author.roles, name="Middle Man")

msg = await bot.wait_for('message', check=check)
await channel.send(f'!rename {str(msg.author).split("#")[0]}')
#

its like this basically

#

inside of check func u put ur condition

limber bison
#

get my point ?

faint sapphire
#

😐

limber bison
faint sapphire
#

but thats how to verify if the name in a message is a role in the guild

#

ure gonna have to use these two things

slate swan
#
async def create_balance(user):
    async with bot.db.cursor() as cursor:
        await cursor.execute("INSERT INTO bank VALUES(?, ?, ?, ?)", (0, 100, 500, user.id))
    await bot.db.commit()
    return

async def get_balance(user):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT wallet, bank, maxbank FROM bank WHERE user = ?", (user.id))
        data = await cursor.fetchone()
        if data is None:
           await create_balance(user)
           return 0, 100, 500
        wallet, bank, maxbank = data[0], data[1], data[2]
        return wallet, bank, maxbank

async def update_wallet(user, amount: int):
    async with bot.db.cursor() as cursor:
        await cursor.execute("SELECT wallet FROM bank WHERE user = ?", (user.id))
        data = await cursor.fetchone()
        if data is None:
           await create_balance(user)
           return 0
        await cursor.execute("UPDATE bank SET wallet = ? WHERE user = ?", (data[0] + amount, user.id))
    await bot.db.commit()

@bot.command()
async def balance(ctx: commands.Context, member: discord.Member = None):
    if not member:
        member = ctx.author
    wallet, bank, maxbank = await get_balance(member)
    em = discord.Embed(title=f"{member.name}s Balance")
    em.add_field(name="Wallet", value=wallet)
    em.add_field(name="Bank", value=f"{bank}/{maxbank}")
    await ctx.send(embed=em)```
#

why isnt it workinhg

#
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 366, in balance
    wallet, bank, maxbank = await get_balance(member)
  File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 343, in get_balance
    async with bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 192, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python310\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'db'```
silk fulcrum
silk fulcrum
#

the fact that you have a db file doesn't mean it automatically creates an attr for you

slate swan
#

i did that elso

#

@bot.event
async def on_ready():
print(f"{bot.user.name} is online!")
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s)")
except Exception as e:
print (e)
bot.db = await aiosqlite.connect("bank.db")
await asyncio.sleep(3)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXITS bank(wallet, INTEGER, bank INTEGER, maxbank INTEGER, user INTEGER)")
await bot.db.commit()
print("Database ready")

#

@silk fulcrum

silk fulcrum
silk fulcrum
slate swan
#

thank you so much!

silk fulcrum
#

By the way syncing in on_ready is also very bad, like almost everything in on_ready is bad at least because it's triggered multiple times.
Where you should sync is in the command (what I mean is you create a command to sync your slash commands), you could also use jishaku's sync command.
And you should only sync when some changes to the slash commands were made, for example a name or a description has been changed. Do not sync when you made changes in the main code of the command, only for the things that discord shows: names, descriptions, permissions, e.t.c.
@slate swan

slate swan
silk fulcrum
slate swan
#

yes

silk fulcrum
# slate swan yes

I don't think there is a fresh example of doing cogs, because they were recently made async (in dpy 2.0)
In this example what I've sent about setup hook there is an example of making cogs (https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#setup-hook)
And here there is an example of making commands and stuff like that in a cog (don't look at how they load the cogs, it has changed, so do it as shown in first gist) https://gist.github.com/EvieePy/d78c061a4798ae81be9825468fe146be
Or if you want to make slash commands in cogs, then this gist: https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32

slate swan
#

all of the files

silk fulcrum
slate swan
#

like

silk fulcrum
#

all of the cogs?

slate swan
#

yes!

faint sapphire
#

when u host a bot on heroku or daki
and u upload the files with a db file
they script is unable to update the db?

#

i tried using oracle but theres an availability issue

silk fulcrum
# slate swan yes!

You should've probably read what I sent.
The main file loads them all here:

    async def setup_hook(self):
        ...

        # Loading cogs
        for cog in myCoolCogs:
            await self.load_extension(cog)``` (<https://gist.github.com/Master326486/6cf48c1ca0509b98e673451e356ba625#setup-hook>)
slate swan
#

oh hh

silk fulcrum
#

That will "run all of them" if that's how you want me to say it

slate swan
#

thank you so much!

silk fulcrum
mighty pilot
#

how do i use @tasks.loop(time=15:30:00) properly? looked at the documentation for it and cant seem to figure it out

silk fulcrum
faint sapphire
silk fulcrum
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
silk fulcrum
#

oh there is time

faint sapphire
#

i mean a cog

mighty pilot
#

got it working with loop(time=seconds) but i saw that is an option so i wanted to explore it lol

silk fulcrum
#

well it's datetime anyways

faint sapphire
#

or like this

@bot.listen()
async def on_ready():
compareUpdates.start()

@tasks.loop(hours=1, reconnect=True)
async def compareUpdates():

silk fulcrum
#

not 15:30:00

mighty pilot
#

i figured it wasnt 153000 i just wanted something to throw in there

#

weird emoji but ok

silk fulcrum
#

:30:

#

:no_nitro_sadness:

mighty pilot
faint sapphire
#

i found it on github when browsing

silk fulcrum
mighty pilot
#

to learn 😮

#

how would i know when i need it if i dont know what it does

#

or how to use it

silk fulcrum
#

@faint sapphire what does that do

faint sapphire
#

task.loop to loop tasks

silk fulcrum
#

no, what does "use a class and rununtilcomplete to call the class or asyncio " do

faint sapphire
#

i mean i meant this

silk fulcrum
#

like how is it different from this

@tasks.loop(minutes=5)
async def oh_god_so_good():
    yesss()```
faint sapphire
mighty pilot
#

from the little bit of reading ive done it sounds similar to an event scheduler to run something at a specified time. i could be wrong but thats why i want to learn

silk fulcrum
# faint sapphire

I'm not even gonna talk about this code, and how bad it is. And, about tasks, I don't see anything different, you just added that if the cog is unloaded then it stops

faint sapphire
#

i know, i rushed things

silk fulcrum
#

for example you can change bot's presence every 5 mins

#

or smth else every <time>

mighty pilot
#

yea i got that much but i wanna know about that time part as opposed to minutes or hours

silk fulcrum
#

!d datetime.time If you don't know how to make a datetime.timeobj

unkempt canyonBOT
#

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
All arguments are optional. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
plucky forge
#

I have another problem

#

i have installed discord-components and i don't know why it sends me this error

mighty pilot
#

from my understanding it wants (time=time(xx,xx,xx)) which is why i came here to ask, because that didnt work lol

slate swan
#

say like a string is 5e712ecf-2fbb-4f37-a462-155917378803 , how would i check how many "-" are in said string and if it has less or more than four say that is invalid help me

faint sapphire
#

who uses digital ocean

slate swan
#

with discord.py is it possible to clear this from the screen

drifting arrow
#

What's a good reddit community to release my discord bot to?

#

It's just a generic discord bot for any discord server

#

I just want as many people to have it as possible ;D

cloud dawn
unkempt canyonBOT
#

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

4
cloud dawn
#

!d str.count

unkempt canyonBOT
#

str.count(sub[, start[, end]])```
Return the number of non-overlapping occurrences of substring *sub* in the range [*start*, *end*]. Optional arguments *start* and *end* are interpreted as in slice notation.
primal token
slate swan
#

lmao what

primal token
#

?

slate swan
#

doesnt make sense what u said

primal token
#

I'm pretty sure those are logging messages from the logger that was setup in discord.py's source, which if you setup a logger depending on the level it would listen to the messages of that logger and sent then into stdout/cout

edgy plinth
#

it wont catch if its a bot

if message.author.bot or message.attachments or str(message.author.id) not in Admins:
    return #exit function
  elif content[0] == prefix:
    print("entered")
cloud dawn
edgy plinth
#

true

faint sapphire
#

should I enable these, idr understand the implications

#

idk what the point of enabling ipv6 is

edgy plinth
#

nvm im stupid

cloud dawn
#

Lol

shut tendon
#

Hey guys, how can I revoke the permission to see a text channel with my bot. My bot already gives the user mentioned the "muted" role and restrict it, but obviously not in text channels. What can I do?

cloud dawn
#

Why not use the built in timeout?

shut tendon
#

wow, i didn't look into it till now, thank u!! I'll look more

grand hedge
#

Hi, I'm new to coding and im just trying to get commands to work can anyone help me? This is what I have and it gives me no errors but doesn't work. I think its a problem with intents but i dont know how to fix it

faint sapphire
#
Response:     fzSftp started, protocol_version=11
Command:    open "root@IPaddress" 25061
Error:            Connection timed out after 20 seconds of inactivity
Error:            Could not connect to server

when trying to use filezilla with a ubuntu vps on digital ocean
anyone able to help?

#

its not possible to use filezilla when using ssh?
i have to change it to a password authentication?

mellow snow
#

Can someone help me with pyqt? there #help-lemon PLS!!!!

slate swan
#

guys can someone help me on how do have multiple commands in a discord bot?

feral lichen
#

help, this was working now it somehow magically isnt ```py
for i in range(0, len(testrange2)):
if testrange2[i].name in teams:
try:
te = testrange2[i]
e = discord.Embed(title='Error', description=f"{member.mention}{member} is already in The {te.mention}{te.name}", color=0xEE1010)
e.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon.url)
e.set_thumbnail(url='https://emojipedia-us.s3.amazonaws.com/source/skype/289/cross-mark_274c.png')
await ctx.respond(embed=e, ephemeral=True)
return
except:
return await ctx.respond('error debug code 7')

tidal hawk
hushed galleon
#

unknown interaction just means your code somehow took too long to respond

tidal hawk
#

ah nvm hes just trying to find right elem

hushed galleon
#

if it happens very occasionally you might just have a funky internet connection

slate swan
#

from discord import Webhook, RequestsWebhookAdapter, message
ImportError: cannot import name 'RequestsWebhookAdapter' from 'discord' (C:\Users\Chain\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_init_.py)

lyric patio
#

i dont understand the module object is not callable

glad cradle
cloud dawn
#

And you need intents

grand willow
lyric patio
cloud dawn
#

!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. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

lyric patio
#

thank you

cloud dawn
#

In this case you can just do an empty intents but it's a required kwarg

slow fog
#

your token isn't define

#

you must define a string variable named token that has your bot's token

slate swan
#

guys i need help, when i run a command i want the bot to DM the output to the person instead of sending the output in the server. the bot is interactive

#

by saying "the bot is interactive" i mean that every person can use the commands on the bot

slow fog
slate swan
grand hedge
slate swan
#

or i can think of something better, how can I make the bot interactive only through DMs?

#

that will be more practical i think

slate swan
slow fog
#

thats a syntax error

slate swan
#

alright i figured it out

#

but the bot is still interactable through the server

slow fog
#

it must be something like this

slate swan
slow fog
slate swan
#

its a mess ik

slow fog
#

you should pass it under each command that you want it to be only in dms

slow fog
slate swan
slow fog
#

thats the name of whatever your command is

#

dont you already have some commands?

slate swan
#

oh right

#

i do, and its already put there

lyric patio
slate swan
#

yoo @slow fog it works now tysm

slow fog
grand willow
lyric patio
#

and now that error popped up

grand willow
#

U didnt do it correct

lyric patio
#

oh.. how do i do it?

grand willow
wicked atlas
#
intents = Intents.default()

client = commands.Client(intents=intents)
mighty pilot
#

whats the best option to keep a long list out of the middle of my code? json file?

#

something i plan to pull things from later with random.choice

hushed galleon
#

storing your list in another file should work fine in any format you want

#

though if you read from it too often, it might noticeably block your bot's event loop

edgy plinth
#
 #Commands
    commands = ["delcare","test"]
    declare_commands = ["occupy","test"]
    
    content = split(message)
    content_word = content[0] #Getting first word
    content_prefix = content_word[0] #Getting prefix / very first letter
    content_word = content_word[1:] #letters after prefix
    content_id = "None."
    print(type(content_word))
  if content_prefix != prefix: await message.channel.send("{} Prefix not recognised, Use `{}`.".format(message.author.mention,prefix)) #Checking if it is the correct prefix
  elif content_word not in commands: await message.channel.send("{} Command not recognised".format(message.author.mention)) #Checking if it is inside commands
  else: #prefix recognised & command recognised

I have no clue why but if i put "declare" it says its not recognised?

any ideas on why?

hushed galleon
#

well your list has delcare instead of declare, but are you writing a custom command parser for your discord.py bot?

edgy plinth
#

oh

#

i hate this, ive spent hours and small typo...

hushed galleon
#

are you sure the built in commands extension isnt good enough for your use case?

edgy plinth
hushed galleon
#

it does take quite a bit of effort when you start adding more features, but if thats enough for your bot then its fine

edgy plinth
edgy plinth
hushed galleon
#

well, just make sure you get it right because technical debt's not fun to deal with

sage glade
#

I dont know how to fix this. im trying to make a command that will send a message with a button

mighty pilot
hushed galleon
#

though discord-components is obsolete given that discord.py and its popular forks already support slash commands and message components

sage glade
#

im back with another question

#

how do i fix Traceback (most recent call last): File "main.py", line 18, in <module> bot = commands.bot(command_prefix='D!', intents=intents) TypeError: 'module' object is not callable
My code is intents = discord.Intents().all() bot = commands.bot(command_prefix='D!', intents=intents) bot.author_id = 984583981540442124 # Change to your discord id!!! @bot.event async def on_ready(): print('Logged on as {0.user} '.format(bot), end='') print(f'in {len(bot.guilds)} guilds!') print('D!logs') print('None') game = discord.Game("D!help") await bot.change_presence(status=discord.Status.do_not_disturb, activity=game)

naive briar
brazen stag
#

Can anyone help we with some slash commands

#

Tried googling and couldn't find the user slash commands

#

Like this

sage glade
sage glade
# brazen stag Can anyone help we with some slash commands

I want todo the same thing but according to discord The python distributions are Discontinued so there will be no offical python code add slash commands, but there are modules like "Interactions" but if your using replit.com then 9 times out of 10 it wont work, i will keep you posted if i see anything.

sage glade
brazen stag
#

discord.Option(
discord.Member,
name="User",
description="Choose",
option_type=2,
)

sage glade
#

THANK YOU SO MUCH

#

Please send an example
Example of an example
bot.command async def hello (ctx):

#

@brazen stag

brazen stag
#

wait

sage glade
brazen stag
#

give me 5min?

sage glade
#

ok

#

sure @brazen stag

brazen stag
#
    async def add(self, ctx,user: discord.Option(
        discord.Member,
        name="User",
        description="Choose",
        option_type=2,
    ), code: discord.Option(int, name="Money", description="Amount")):
        if ctx.author.guild_permissions.administrator:
            con = sqlite3.connect("./database.db")
            cur = con.cursor()
            cur.execute("select * from Members where id == ?;", (user.id,))
            data = cur.fetchone()
            if data == None:
                e = discord.Embed(
                    title = "System",
                    description="Not in guild",
                    color=discord.Color.red()
                )
                return await ctx.respond(embed=e, ephemeral=True)
            cur.execute(f"update Member set money = money + {int(code)} where id == ?;", (user.id,))
            con.commit()
            e = discord.Embed(
                title = "System",
                description=f"지급성공\n지급자 : {ctx.author.mention}\n지급받은사람 : {user.mention}\n지급금액 : {code}원",
                color=discord.Color.green()
            )
            return await ctx.respond(embed=e, ephemeral=True)```
#

well, this code is for a game

#

plz note that

sage glade
#

ok

edgy plinth
#
def is_neighbour(Regions,Faction,id):
  for Region_selected in Regions:
    owner = Region_selected["owner"] #each owned region by occupier
    if owner == Faction:
      for i in range(len(Region_selected["neighbours"])):
        neighbour = Region_selected["neighbours"][i]
        if int(id) == int(neighbour):
          neighbour = True
          print("FOUND")
          return neighbour

i cant set owner without it erroring (region looks like this {'id': 104, 'owner': 'None', 'neighbours': [103, 105, 115, 118, 114, 94], 'building': 'None', 'water': True, 'price': 2})

brazen stag
# sage glade ok

if you want to do a role change discord.Member to discord.Role

sage glade
#

okk

robust fulcrum
#

Guys why i getting this error again and again

edgy plinth
robust fulcrum
sick birch
robust fulcrum
#

Termux

sick birch
#

Are you hosting it locally?

robust fulcrum
#

On my mobile device

sick birch
robust fulcrum
#

I not hosting i just running it

sick birch
#

Then somewhere in your code you're spamming discord with requests and getting ratelimited

sage glade
robust fulcrum
#

I got this error now

robust fulcrum
sage glade
brazen stag
sage glade
brazen stag
#

is it pycord?

sage glade
brazen stag
#

if you are discord py you will need to use another code

sage glade
#

let me go install pycord hold on

brazen stag
#

well using a slash command is better on pycord

sage glade
#

ok

brazen stag
#

or do pip install discord-py-slash-command on cmd

#

idk if that will work

#

use this also

robust fulcrum
#

Guys how can I exit discord bot running i mean how to stop bot running in termux?

brazen stag
#

Making your bot of in termux?

sage glade
# brazen stag

Traceback (most recent call last): File "main.py", line 17, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash'

sage glade
sage glade
#

ok

solid ice
#

Hi im using bridge commands with one parameter.
when i use the slash command /command in discord i can see the parameter and discord dont let me submit without providing the value.

But with just prefix command !command i can just submit and in the console i get error discord.ext.commands.errors.MissingRequiredArgument: food is a required argument that is missing.

I understand that it is required to pass !command food but is there any built in validation that pycord provides to handle this instead of catching every missing arguments ?

code:

@bridge.bridge_command()
async def find_nutrition(self, ctx: commands.Context, food: str):
  await ctx.respond(f"You searched for {food}")
sage glade
# brazen stag Change Give -> give

same error Traceback (most recent call last): File "main.py", line 17, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash'

brazen stag
#

using pycord?

naive briar
sage glade
solid ice
#

ehh dont they have any built in for that ?

naive briar
#

Like typing.Optional?

solid ice
#

no, i mean validation error msg to user when they dont pass argument

#

i mean i dont want to make 1000 try catch for every commands.

#

oh wait can i make an error handler at global instead of every command ?

naive briar
solid ice
#

Mhm

naive briar
naive briar
solid ice
#

Ahhh i see, thanks let me try

sage glade
brazen stag
#

use two files

#

one only for slash commands

sage glade
#

ok

naive briar
solid ice
#

yeah i just found in their docs

sage glade
sage glade
brazen stag
#

uh..

#

i use vsc?

sage glade
#

ops wrong message

sage glade
sage glade
sage glade
brazen stag
sage glade
sage glade
silk fulcrum
vocal snow
sage glade
silk fulcrum
sage glade
silk fulcrum
#

second pin

steep river
#

can I stop an on_message_edit? that or make after.content revert back to before.content?

vocal snow
#

you can do the latter if the message was sent by the bot

sage glade
steep river
vocal snow
#

you can't edit messages sent by other users

#

or stop them

#

you could delete the message, or use a webhook to "mimic" the old message

steep river
#

ah oh well

#

thanks though!

naive briar
#

The error is literally telling you

#

Look at Did you mean

#

What is original_message?

#

!d discord.Interaction.edit_original_response - There's only edit_original_response

unkempt canyonBOT
#

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

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
naive briar
#

type object 'Interaction' has no attribute 'edit_original_message'. Did you mean: 'edit_original_response'?

#

Hmmm

#

Did I read anything wrong?

#

Well uhhh

#

Look like there's an error in the library

#

I did misread it 😿

naive briar
vocal snow
#

The last line even suggests what's wrong

naive briar
slate swan
#

pycord moment ;-; ask em to update it

naive briar
#

Classic

vocal snow
#

You should uninstall discord.py and other discord api libraries

sage glade
#

my rate is being limited

vocal snow
#

Ok

sage glade
#

ok send me the code VIA DMs

#

the bot code, WITHOUT TOKEN

#

agreed

#

atleast the error

vocal snow
#

It's not like you need the bot code to fix the error

sage glade
#

yeah

slate swan
#

why are you using that version when 2.1.3 is the latest release

sage glade
#

thanks

vocal snow
#

😂

slate swan
#

epik

vocal snow
#

Pycord is truly something wonderful

slate swan
#

and wtf they create a subclass ApplicationContext object using abc. Messageable 🗿

#

not related to your issue, just kinda triggered me

honest shoal
#

InteractionContext

slate swan
#

anyways do you have a folder called local or bin in the container?

#

go thru it
find a folder names site-packages
lookup for pycord/ discord
open the file mentioned in the error
and replace the erroring attribute with the correct one

sage glade
#

looks like you used the wrong attribute or variable. check the pycord docs

slate swan
#

thats a pycord internal error tho, he did nothing wrong in his code

#

should be bin

maiden fable
#

Nice, none of the profile pics are loading

slate swan
#

check the lib folder

#

yes now look into the discord folder

#

and find your file from which error comes

#

yes which means the library was installed

#

consider resetting the python package installations

naive briar
#

Go to commands folder

#

Not ext/commands tho

#

I meant discord/commands

#

Go to back to discord

#

Then go to commands

#

context.py

#

Try running your bot again

vocal snow
naive briar
#

Good idea

silk fulcrum
#

would be a good idea tho

#

what is that import ..., main in your main.py?

#

im talking about the import ..., main in your main.py

#

not sure about what?

#

nor am I

#

I don't know what is that main, and what do you use it for so nothing I can say

#

It might be a cause of this error

#

might not

silk fulcrum
#

Let's see what you're doing step by step:

  • result = all of channels (ids) that have autoreacts
  • loop through result (work with each channelID)
  • check if channelID is the current channel id:
    -- if yes:
    --- delete autoreact
    -- else (if no):
    --- say that there is no autoreact in this channel
    Can you find a logic mistake or should I explain it?
#

no

#

So you loop through each of autoreact channels.
That means that if there is two or more channels with it then it will get autoreact_channel_id_1
and check if it's your channel id, but your channel is autoreact_channel_3 so it will say that there is no autoreact in this channel, even though there is.
Then it continues the loop, but since you can only respond to an interaction once, when it gets to autoreact_channel_2 it will try to send that there is no autoreact again but will fail.

What you should do instead is check if your channel is in the list of autoreact channels ids, like this if channel.id in [c[0] for c in result]: and then delete the autoreact, or if it is not (else:) then send that there is no autoreact
NOTE: [c[0] for c in result] does the same as for eintrag in result: c = eintrag[0], just puts it in a list

#

You didn't do what I said

#

Your code should look like this:

if channel.id in [c[0] for c in result]:
    await cursor.execute(...)
    await interaction.response.send_message("Deleted!")
else:
    await interaction.response.send_message("No autoreact here.")```
#

you took the note too seriously i guess

#

It was just an explanation of what [c[0] for c in result] does

#

channelID = eintrag[0] is odd there

#

remove

#

wdym :wtf:

#

how

#

what is in your code

#

audit logs

#

check audit logs

#

they usually give clear info about what is happening

#

in this code there is no deleting messages

#

okay so its not bulk

#

then no idea

#

go ask your friend is he dumb

#

maybe he is using self-bot

#

or he is being hacked

#

or wait

#

I think you have automod

#

in your bot

#

then no idea

#

this is discord bots tho, not stupid friends

naive briar
#

You have a function named set?

silk fulcrum
#

it is shadowing

#

you shouldn't name anything like a builtin name

#

Not use set as a name for a group

#

either rename it to something else or maybe to _set

naive briar
#

Event

slate swan
#

guys how to make requirements.txt

fresh ferry
#

idk if this is the right place but im wanting a pay a python discord bot dev to make me a bot, where is the best place i can find one, fivver is out of the question, too many bad experiences with them

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
fresh ferry
#

i wasnt asking anyone on here but you do you bub

shell wing
fresh ferry
naive briar
#

!d discord.on_guild_emojis_update

unkempt canyonBOT
#

discord.on_guild_emojis_update(guild, before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") adds or removes [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

This requires [`Intents.emojis_and_stickers`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.emojis_and_stickers "discord.Intents.emojis_and_stickers") to be enabled.
slate swan
fresh ferry
shell wing
slate swan
#

oh alr thanks

shell wing
#

sure np

slate swan
#

@shell wing

discord.ext
os
discord
asynico
re
datetime
aiohttp
io
nextcord
random

shell wing
#

yups

slate swan
#

like this?

slate swan
# shell wing yups

ERROR: Could not find a version that satisfies the requirement discord.ext
ERROR: No matching distribution found for discord.ext

shell wing
#

discord.ext isnt a package from pypi

slate swan
shell wing
#

discord-ext-bot

#

u need to use the name that are given in pypi website....

naive briar
# slate swan so how do I write it as?

Let's say we have this:

from aiohttp import ClientSession
from discord.ext import commands
import discord

In requirements.txt it'll look like this

aiohttp
discord.py
brazen raft
#

The library also installs other libraries

#

Most likely

naive briar
#

(Just for the example 🥺)

brazen raft
#

Yeah but you don't need the requirement for aiohttp

#

Unless you need a specific version

slate swan
#

so I deleted

naive briar
naive briar
brazen raft
#

May I ask what's the problem

slate swan
brazen raft
naive briar
brazen raft
#

The quickest way is to put in a requirements.txt file the output from running pip freeze

slate swan
# naive briar It's a stdlib

ERROR: Could not find a version that satisfies the requirement stdlib
ERROR: No matching distribution found for stdlib

brazen raft
#

Unless you have other unnecessary libraries installed on which the project does not depend

slate swan
#

wait no

#

I have to install random

brazen raft
#

You don't

slate swan
#

yes I do

#

I deleted random and it showed another error

brazen raft
#

It's a module in the standard library, you don't need to install it externally

slate swan
#

just tell me how random sounds like in requirements.txt

brazen raft
#

You should not list standard library modules in that file

slate swan
#

just tell me how does random sound in requirements.txt

brazen raft
#

It seems like you have an error in another area of the project

brazen raft
#

Or rather I should say a problem

slate swan
#

when I remove random it shows error

brazen raft
#

What error

slate swan
#

bro just say how does error sound in requirements bruh

brazen raft
#

What is your traceback

slate swan
#

why wasting time

brazen raft
#

It doesn't seem possible to me to get an error about a missing standard library module

#

Have you tried repairing your Python version

slate swan
#

..

brazen raft
#

It's possible if you have the installer

slate swan
#

I just need to know how does random sound in requirements..

brazen raft
#

It sounds like you have a problem elsewhere

naive briar
slate swan
#

it shows this everywhere when I remove import random

#

now how does random sound in requirements

naive briar
brazen raft
#

Is random being imported by the file that raises the exception

slate swan
brazen raft
slate swan
#

just tell me how does random sound in requirements

#

tell me how "random" is written in requirements

naive briar
#

random is a standard library that comes with Python

#

Why would you want to add it in there

brazen raft
#

If the file needs import random, add that line at the top of it

#

You don't need to list it

#

Everybody with Python has it

slate swan
brazen raft
#

The standard library modules mostly come in tact with every Python version

#

Maybe they have changes or maybe they don't have support for some platforms

slate swan
#

random in python 1.x 🐍🥔

brazen raft
unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
#

the error..

brazen raft
#

!paste paste it here and send the link

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

the error..

brazen raft
#

I am not able to see it clearly right now as it is small and I am under direct sunlight

#

Is all of it the traceback

slate swan
slate swan
#

alr lemme change

#

you asked your host to run bot.py and didn't provide them

#

ikik

#

my bad

#

ok it finally worked

brazen raft
upbeat gust
#

!d discord.on_guild_emojis_update

unkempt canyonBOT
#

discord.on_guild_emojis_update(guild, before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") adds or removes [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").

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

this event is called when emojis are updated

#

compare the before and after to find what was added

slate swan
#

Hey!

How would would i make it so when i run a slash command i get the options true or false

Like this

#

Code:

@bot.slash_command(description="Play rps with the bot")
async def rps(ctx, choice:discord.Option(str, "rock, paper, or scissors all lowercase", required=True)):
    rpsGame = ['rock', 'paper', 'scissors']
    user_choice = choice
    comp_choice = random.choice(rpsGame)
    if user_choice == "rock":
        if comp_choice == "rock":
            embed=discord.Embed(description=f"Well, thats weird... We tied??")
            embed.add_field(name="Your choice", value=choice, inline=False)
            embed.add_field(name="My choice", value=comp_choice, inline=False)

and so on

#

but i want it so they have a list of options not they type it

slate swan
#
@bot.tree.command(name="help", description="Use help to see all of my commands")
async def helpme(interaction: discord.Interaction):
    await interaction.response.send_message(f"!mute - Mutes A Member \n !unmute - Unmuted A Member \n !h - Use that command to get help from the staff! \n!say (text) - Says Something", ephemeral=True)```
#

its not working

brazen raft
unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
brazen raft
#

Never mind then

slate swan
#
@bot.tree.command(name="help", description="Use help to see all of my commands")
async def helpme(interaction: discord.Interaction):
    await interaction.response.send_message(f"!mute - Mutes A Member \n !unmute - Unmuted A Member \n !h - Use that command to get help from the staff! \n!say (text) - Says Something", ephemeral=True)```
#

does anyone know why its not working

slate swan
brazen raft
slate swan
#

ive been waiting more then a hour

#

its not working

brazen raft
#

Try syncing it manually with tree.sync

slate swan
#

ill try

brazen raft
#

It needs to be awaited, and you can also sync it by providing some discord.Object with the guild's ID for it to sync to the guild immediately first

upbeat gust
brazen raft
slate swan
#

Traceback (most recent call last):
File "C:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 50, in <module>
@bot.tree.sync(name="help", description="Use help to see all of my commands")
TypeError: CommandTree.sync() got an unexpected keyword argument 'name

slate swan
upbeat gust
#

You can't sync one command

#

Where'd u get that from

slate swan
brazen raft
slate swan
#

thought it was it

naive briar
#

What are you trying to do

upbeat gust
#

Why are you converting it to string, then back to a role object with utils.get

naive briar
#

Why are you getting the roles again

upbeat gust
#

just keep it as set() - set(), that'll give one Role object

#

All of the str, join, utils.get is unnecessary

#

Wait why are u making it a set anyway

glad cradle
upbeat gust
naive briar
#

You're trying to get member's avatar?

#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
naive briar
#

Yes

#

It returns discord.Asset btw

slate swan
#

how do I make my Discord Bot work 24/7 (replit / visual studio code, python)

slate swan
upbeat gust
vale wing
#

You can get guild object with its ID and then access name attribute, just like this

guild = bot.get_guild(id)
name = guild.name```
slate swan
#

guys how do i make only certain roles be able to use commands for my discord bot

pulsar solstice
#

how to write something in a txt using aiofiles in each line

slate swan
tidal hawk
#

Mhm, you can use same logic to implement it on your own roles

#

Or you can also just check inside the command, if the user has certain role

slate swan
#

i am making a bot that you have to purchase to use first, thats why im trying to do this, for now everyone has access and i want only people with the role "buyer" to be able to access the role

#

or maybe a key system would be more efficent

#

like you have to redeem a key to be able to use a bot

vocal snow
#

you should use a database

#

store the user id, their "plan", and other data you require

slate swan
vocal snow
slate swan
#

im new to making discord bots, i made something but the bot works even without redeeming the key

placid verge
#

How do you set a minimum length for a slash command's argument?

#

For example They have to enter at least 10 characters in order to send the slash command

tidal hawk
rugged shadow
#

if not, you should probably have some sort of file that contains all the buyers user ids

#

or even better, use the db

slate swan
#

alright i came up with something

tidal hawk
#

oh

slate swan
#

and now when i try to run pip this pops up
Fatal error in launcher: Unable to create process using '"C:\Users\Nikola\AppData\Local\Programs\Python\Python310\python.exe" "C:\Users\Nikola\AppData\Local\Programs\Python\Python310\Scripts\pip.exe" list': The system cannot find the file specified.

rugged shadow
#

oh well you can just override the bot's on_message method and return if the author doesn't have the role

slate swan
#

it says
Requirement already satisfied: pymongo in c:\users\nikola\appdata\local\programs\python\python310\lib\site-packages (4.2.0)
but it doesnt work when i try to run mongoclient in my program

#

don't use pymongo though, use motor which is basically the async driver of Pymongo

shrewd apex
slate swan
#

the command MongoClient still isnt working

shrewd apex
#

absolutely

slate swan
#

i dont know what to put here instead

night glen
#

new to python here, how can I make this not case sensitive lol

if message.content == "Hello":
        await message.channel.send("Hi")
#

in nodejs, I'd use ==, if I wanted it to be case sensitive, I'd use ===

#

not sure how to do this in python though

slate swan
#
kategoria4 = await ctx.guild.create_category("━━━━━ GŁOSOWE ━━━━━")
        await kategoria4.create_voice_channel("『🔱』ogólny", user_limit = 99)
        await kategoria4.create_voice_channel("『🤬』tyralnia", user_limit = 99)
        await kategoria4.create_voice_channel("━━━━━━━━━━━━━", user_limit = 99) #how to add conect false?
        await kategoria4.create_voice_channel("『🔱』ogólny", user_limit = 99)
        await kategoria4.create_voice_channel("『🔱』ogólny", user_limit = 99)```
#

how to add conect = false?

tidal hawk
night glen
#

ty

naive briar
slate swan
#

can't join voice channel

#

nobody

#

V

#

so?

naive briar
slate swan
naive briar
#

You can either edit the channel's permission or create the channel with the desired overwrites

slate swan
#

and what does this inscription look like?

#

!d discord.VoiceChannel.set_permissions

unkempt canyonBOT
#

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

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

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

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

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

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

and?

#
        zablokowane = await kategoria5.create_voice_channel("━━━━━━━━━━━━━", user_limit = 99) #how to add conect false?
        await zablokowane.set_permissions()```
#

@tidal hawk will you finish writing today?

tidal hawk
#

I like to write

slate swan
#

when i try to run my bot which uses mongoclient i get this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationFailure: bad auth : Authentication failed., full error: {'ok': 0, 'errmsg': 'bad auth : Authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}

slate swan
unkempt canyonBOT
#

await create_voice_channel(name, *, reason=None, category=None, position=..., bitrate=..., user_limit=..., rtc_region=..., video_quality_mode=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

This is similar to [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
slate swan
#

join_channel mb

slate swan
#

plss help me with this

naive briar
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot 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

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

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

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

tacit prairie
#

[ERROR]: Message contents cannot be null what is that

naive briar
tacit prairie
#

Content is not a none

#

I know what is that

#

I asking how i can fix it

hushed galleon
#

the traceback suggests that your embed didnt have anything inside it

slate swan
hushed galleon
#

you'll need to show the code for your help command if you want us to find out why its empty

naive briar
slate swan
hushed galleon
#

then just send your help command in a paste

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

@naive briar

naive briar
hushed galleon
tacit prairie
tacit prairie
naive briar
hushed galleon
tacit prairie
#

The problem is in soruce

hushed galleon
#

the API reference sure, but the docs unfortunately dont have their own guide for using interactions/app commands

robust fulcrum
#
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/commands.py", line 861, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "/storage/emulated/0/Download/ProGamerzbot/cogs/game.py", line 159, in _wild
    await inter.response.send_message(file=file,embed=embed1)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/interactions.py", line 762, in send_message
    await adapter.create_interaction_response(
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/webhook/async_.py", line 218, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'wild' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

Guys how can I fix this error?

tacit prairie
#

1 month ago that cmd is worked

naive briar
naive briar
robust fulcrum
glad cradle
hushed galleon
# hushed galleon the API reference sure, but the docs unfortunately dont have their own guide for...

@hidden hazel you could go through the app commands / message component examples on the github and check out ashley's slash command guide in the second top pin of this channel, you'll find that the process essentially boils down to a user triggering an interaction and your bot answering to the interaction

the github examples: https://github.com/Rapptz/discord.py/tree/master/examples (inside app_commands/ and views/)

untold iron
#

How can i make it so commands only work based on a condition e.g. if its a specific channel?

i.e. if i have a command to create a new channel, then in that new channel i want to only be able to execute command x, command x can only be executed in that new channel made no where else

night glen
#

I'm new to python, this doesn't do anything for some reason?

@client.command()
async def ping(ctx):
    await ctx.reply(f"Pong! {round(client.latency * 1000)}ms")
#

command_prefix is set to !

#

I don't get any errors or anything

naive briar
night glen
silk fulcrum
untold iron
#

Ahh thank you bro

naive briar
untold iron
#

That helps me im going to try implement it later

silk fulcrum
night glen
silk fulcrum
#

ok, it is not

night glen
#

I do bots in discord.js lol, I could make a ping command really easily if this was nodejs

#

I've made multiple commands with the same bot in nodejs

silk fulcrum
#

nope

#

it's just something wrong in your code/bot/idk

slate swan
naive briar
night glen
naive briar
slate swan
silk fulcrum
slate swan
#

or what catgal said, works both ways

night glen
#

yeah, it works now, did .listen()

slate swan
untold iron
#

How can i bring a variable frm one function into a new function?

dull terrace
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | a string
002 | 123
dull terrace
vale wing
#

Jaja

dull terrace
#

best way if you can't pass between functions is to make a config.py and import it

slate swan
#

its useful in many cases, except not in a Discord bot

untold iron
slate swan
vale wing
#

As for discord bots use a "botvar" or a separate module

slate swan
#

oop, but this works too

vale wing
#

Depends what exactly you want to store in the var and how your code is organised

primal token
dull terrace
primal token
#

You never passed a variable kek

vale wing
#

That's not really "between"

dull terrace
vale wing
dull terrace
#

!e

def okay(this):
  print(this)

def asdf():
  this = "sdafsad"
  okay(this)

asdf()```
unkempt canyonBOT
#

@dull terrace :white_check_mark: Your 3.11 eval job has completed with return code 0.

sdafsad
primal token
#

The question is still arbitrary

#

#bot-commands

dull terrace
patent fjord
#
    @discord.ui.button(label='reload', style=discord.ButtonStyle.green, custom_id='persistent_view:reload')
    async def reload(self, interaction: discord.Interaction, button: discord.ui.Button):
        urll = https://image.png
        embed = discord.Embed(title=f'test ! ', description=f"**[🔗you dont see the link? click me]({urll})**", color=0xff97ff )
        embed.set_image(url=urll)
        embed.set_footer(text=f"requested by: {interaction.user}")
        await interaction.response.edit_message(embed=embed)


    @discord.ui.button(label='save', style=discord.ButtonStyle.green, custom_id='persistent_view:save')
    async def save(self, interaction: discord.Interaction, button: discord.ui.Button):
      await interaction.user.send (self.embed.image.url)

im trying to send the embed image url in dm but i cant
who can help me please

vale wing
#

Ok I figured it out, from 1st formulation the man wanted to bring a var from one function to another but I interpreted it as "make the var able to be used in multiple functions" in fact you can read it without making it global if you define it in outer scope but if you need to write you gotta still make it global

#

🤓

dull terrace
#

anyone want to beta test my bot (update), up to 5.5k lines of code now amegablobsweats

vale wing
vale wing
patent fjord
#

its for an exemple

dull terrace
#

no, i got ocd with organizing and

vale wing
#

Ok cool

dull terrace
#

probably too many for config wheeze

vale wing
patent fjord
vale wing
#

Ok what exactly doesn't work

patent fjord
#

i cant save the embed image in the first button

vale wing
#

Oh one sec

#

I got it now

#

You never assign self.embed

patent fjord
#

and i want when the button "save" is clicked the bot send the embed image in dm (without list.append)

patent fjord
vale wing
#

Then how are you going to use it

patent fjord
#

idk

vale wing
#

You gotta assign it in reload function ig

patent fjord
#
    @discord.ui.button(label='reload', style=discord.ButtonStyle.green, custom_id='persistent_view:reload')
    async def reload(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.urll = https://image.png
        embed = discord.Embed(title=f'test ! ', description=f"**[🔗you dont see the link? click me]({self.urll})**", color=0xff97ff )
        embed.set_image(url=self.urll)
        embed.set_footer(text=f"requested by: {interaction.user}")
        await interaction.response.edit_message(embed=embed)


    @discord.ui.button(label='save', style=discord.ButtonStyle.green, custom_id='persistent_view:save')
    async def save(self, interaction: discord.Interaction, button: discord.ui.Button):
      await interaction.user.send (self.urll)
#

like this

night glen
#

how do I make an argument in a command not required?

maiden fable
#

give it a default value

night glen
maiden fable
#

Show the function

night glen
#
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member:discord.Member, *, reason:None):
    if reason == None:
        reason = 'because fuck you, thats why'
    await ctx.guild.kick(member)
    await ctx.send(f"User {member.mention} has been kicked for {reason}")
maiden fable
#

reason: str = None is what u r looking for

#

The : sets a typehint

night glen
#

I did reason=None, that did the trick I guess lol

maiden fable
#

Yup

night glen
primal token
primal token
glad cradle
#

!d discord.Guild.kick

unkempt canyonBOT
#

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

Kicks a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

Whoah since when does discord display discord and server join date :3

sick birch
cloud dawn
#

I don't want frequent updates.

tough lance
#

can you get a file as an argument in slash command?

naive briar
tough lance
naive briar
nova hill
#

hey how can i use a webhook to upload files into a discord channel?

dull terrace
#

Anyone bored and wanna test my game bot? 1 gold star to anyone who finds a bug froggy_chill

nova hill
#

sure?

dull terrace
#

Can i post links here or do i need to DM not to annoy mods

nova hill
#

just dm the link to me

dull terrace
#

sent the link

dull terrace
plucky forge
plucky forge
#

I have installed discord components and I don't know what's happened

#

Or there is something else to install

dull terrace
#

anyone else up for beta testing for my discord game bot? last time i ask froggy_chill

silk fulcrum
dull terrace
silk fulcrum
#

hello.

dull terrace
#

more info here for ya

silk fulcrum
#

I even have a hanging project, I haven't made changes in it for like half a year

#

well just a little bit

tough lance
#

can you make a slash command accessible to only a specific user?

silk fulcrum
#

I feel like when I'm gonna get to continue it's development, discord will already make bots completely useless

#

wait what

tough lance
silk fulcrum
#

how did I miss this update

#

you can do that

tough lance
#

You can grey out the slash command for specific permissions but not user?

silk fulcrum
#

and you can also make a slash command accessible to only one user

#

well it will show up for everyone, but will be accessible only for that person

silk fulcrum
#

but not for certain people
why not?

def prefix_exciting_bruhness(client, message):
    p = await db.get("SELECT prefix FROM prefixes WHERE u_id = %s", (message.author.id,))
    return p

bot = commands.Bot(command_prefix=prefix_exciting_bruhness)```
cloud dawn
silk fulcrum
cloud dawn
silk fulcrum
primal token
#

I wouldnt call wasting your time on discord a flex

#

no offense to the user of course

slate swan
#

If you were to make snake on discord, how would you think of it to go? How would oyu make it\

marble pilot
silk fulcrum
marble pilot
#

Openned urs. Doesnt have it. Hm

#

Shi i see i got an update

#

Ig thats it

primal token
#

Bro check your pings, mobile client doesnt have it yet

marble pilot
#

?

civic pecan
#

how can i make the user a variable?

marble pilot
silk fulcrum
marble pilot
#

Yeah i did

#

Im on mobile. Does that affect it

primal token
silk fulcrum
#

oh

primal token
#

I can say it as my mobile client is up to date and i dont have it

#

That's how discord does it, give new features to the desktop client and after a few weeks or months they give it to mobile clinet

sage glade
#

i am coding on vsc and im getting this error /bin/python3 "/home/danielchudnovsky154/Shape of an L on the forehead/main.py" Traceback (most recent call last): File "/home/danielchudnovsky154/Shape of an L on the forehead/main.py", line 13, in <module> from discord_slash import SlashCommand, SlashContext ModuleNotFoundError: No module named 'discord_slash' and i used pip install -U disscord-py-slash-command help

sick birch
#

Looks like you've got an extra s

sage glade
#

where

sick birch
#

Either way discord.py has native slash commands built in, why do you need discord-py-slash-command anyway?

#

From what I'm hearing the library isn't all that good

sage glade
sick birch
#

Has all of the interactions related stuff

cloud dawn
#

Aka he followed a discord tutorial on youtube.

sick birch
#

unfortunately way too common

sage glade
#

@sick birch i changed from discord_slash to from discord

sick birch
#

the best we can do is spread awareness to just stick with the implementation your fork of choice provides

sick birch
primal token
slate swan
#

CAN ANYONEEEEEEEEEE HELP MEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE

indigo pilot
#

anyone know why

cloud dawn
sick birch
indigo pilot
#

I’ve tried all of it lmao

#

Seems like a lib issue

granite sun
#

Hello, good afternoon person. Has anyone used selenium? I'm not sure how can I leave more than one chrome running together

slate swan
#

hello

#

anyone have a fix for it?

grand willow
#

with ur own you mean one from github right?

slate swan
#

no i bought it

slate swan
primal token
#

it's discord.Bot

grand willow
slate swan
grand willow
#

Maybe also check the file for malicious code I seen a few ppl sell boost bots with malicious code in them

primal token
#

If you couldnt troubleshoot a TypeError how could've you detected malicious code, no offense?

slate swan
#

I am getting this error

cloud dawn
#

Those bots are against ToS