#discord-bots

1 messages Β· Page 535 of 1

odd pendant
#

for consistency

hasty iron
#

what?

slate swan
#

No not that

#

I'm just in shock

slate swan
odd pendant
slate swan
#

No

#

Because a command closes a window

hasty iron
#

a window?

odd pendant
#

probably the console for the bot when it closes

#

dk why it closes tho

slate swan
#

i wont be too shocked if they say the command prompt

hasty iron
odd pendant
#

I guess but usually it would just say that it exited and wait for keypress

#

maybe that's just me tho

slate swan
#

bRUH

#

PYTHON IS COOL

boreal ravine
#

it isnt

odd pendant
#

rust is cooler

boreal ravine
#

use typescript

#

more cooler

lilac latch
#

Wish if coding bots was possible in bash

slate swan
#

whats bash?

lilac latch
slate swan
#

the cool hacking stuff?

lilac latch
slate swan
lilac latch
#

Yes sir

slate swan
lilac latch
slate swan
#

πŸ˜„

lilac latch
#

Lmao good joke tho it wasn't a joke

slate swan
eternal pine
#

why my bot does nt work

slate swan
#

What is the error

#

What doesn't work

#

What do you get

#

What did you expected

eternal pine
#

i have prefix "! "

slate swan
#

Just saying

why my bot does nt work
doens't give any information for us to help

#

And we won't help you anyways

#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
eternal pine
#

and this is Music bot when i want to play somwthing

slate swan
#

Read this

#

We won't help you

eternal pine
#

oh okay

boreal ravine
opaque trail
#

we can help you as long as it doesnt use YTDL

slate swan
opaque trail
#

??? KEKW

slate swan
opaque trail
#

then no helpy bro

wheat ember
#
key = None
# assign key (ctx,*,message)
 global key
 key = message
#use key
 #do something and set key = None

i want to do something like this but it error what i should type in use and set key to None?

slate swan
#

What are you even trying to do

#

This is like really weird to understand and seems messy

#

Can you make that number start from zero again at 12 every night?

wheat ember
slate swan
#
async def get_role(guild: discord.Guild, role: str):
  role_obj = await discord.utils.get(guild.roles, name=role)
  return role_obj

object Role cannot be used in await expression? line 2 btw

harsh mirage
#

GUYS WHAT IS Key for?

wraith bay
#

How to make a antilinks?

dapper cobalt
dapper cobalt
unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
slate swan
willow vine
#

when i run my code locally, its working fine, but when i deploy it on heroku it throws a file not found error
can someone help me with this

slate swan
#

Don't host on Heroku

#

But anyways

#

How is your files structure

willow vine
#

i want to know why its throwing an error

slate swan
#

and what's in your Procfile

willow vine
#

this is the procfile working: python main.py

slate swan
#

Shouldn't be working but worker

willow vine
#

this is my file structure, im trying to read a png file using fr"icon/{name}"

slate swan
willow vine
#

its just having an error with files

slate swan
#

it's worker

#

not

#

working

#

Not chaning that won't make your bot work better in any way either

#

So change it please

#

If you don't even listen to what we say why would we help you further

#

And yes it might be the issue because working might be used for something else and the files structure for that is maybe not the same

#

And that's all I'll say because you seem to be subborn and have a big ego, and I don't want to waste further time with that

willow vine
#

i just asked the doubt, yu were being stubborn in the first place...

slate swan
#

And since it's a reminder bot, you know that heroku clears all your files at midnight and get everything again from your repository right?

#

im trying to check if the bot can ping all the guild members but it only pings itself while theirs 2 more users the code:

for member in ctx.guild.members:
        await ctx.send("member"f"{member.mention}")
#

Enable members intent

#

!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 the Members and Presences intents, which are needed for events such as on_member 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.

slate swan
#

thanks im going to check

willow vine
slate swan
brave flint
#

Well does we can summon friend to our voice chat on guilds?

zenith laurel
#

Does anyone know if there's currently a "best" library that implements slash commands, or one that seems to be pulling ahead in terms of quality? Last I looked there were several, and I know that the maintainer of discord.py is opposed to implementing them in his library and his library was previously the standard

slate swan
brave flint
reef shell
wispy spade
reef shell
#

they have implemented the slash commands

wispy spade
slate swan
#

To be fair I would not use a fork and use another language xD

#

Forks are quite often a mehh option

reef shell
#

time.sleep() is a blocking function , don't use it

sick wedge
reef shell
#

use asyncio.sleep() instead

slate swan
#

ember.fields[index]?

sick wedge
#

i try natives value and the error comes up

willow vine
sick birch
#

e. g manual registration using the API combined with on_interaction

covert lion
#

someone can help me?

#

at line 37

#

at line 377

slate swan
covert lion
slate swan
#

also check the resources for basic python knowledge

covert lion
#

@commands.command() async def pause(self,ctx): await ctx.voice_client.pause()

slate swan
#

I saw it

covert lion
#

why it cant work?

slate swan
#

!indents

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

boreal ravine
slate swan
unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
harsh mirage
#

do u know how to make this (smth like that for my bot)

    get_role:
        (role.id)```
how to add a role by command?
slate swan
#

is it possible to set image on the playing status of bots

slate swan
#

Nope

harsh mirage
#

Hello! I will appriciate if someone could help me! I'm making an Add role system for my bot. Something like if you type !freerole1 it will give you specific role. Thanks!

marble pilot
#
    @commands.command()
    @commands.guild_only()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount):
        try:
            task_embed = discord.Embed(title=f"{amount} messages have been cleared.",
                                       color=discord.Colour.blue(),
                                       timestamp=ctx.message.created_at)

            await ctx.channel.purge(limit=int(amount))
            msg = await ctx.send(embed=task_embed)
            await asyncio.sleep(3)
            await msg.delete()

        except Exception():
            given_type = type(amount)
            error_embed = discord.Embed(title="Error. Amount should be an integer.",description=f"{amount} is a {given_type}. ",color=discord.Colour.red(),timestamp=ctx.message.created_at)
            await ctx.send(embed=error_embed)

Ok so im making a clear command and i want to send at the embed how many messages actually got deleted. Like if the input is 500 but there are only 10 messages in a channel then i dont want it to send "500 messages got cleared" i want it to send 10. Do i make a for loop for that or what?

marble pilot
marble pilot
#

srry didnt want to ping you

slate swan
#

So store it, and get it's length

#

Then you know how many messages got deleted

dapper cobalt
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
dapper cobalt
#

Ah. Already solved, my bad.

slate swan
#

Pretty sure there's also an example on the documentation

#

So you can check it out there

marble pilot
marble pilot
dapper cobalt
marble pilot
#

Hm my solution works for me

marble pilot
#

just created a var

#

to store ctx.author

slate swan
#

Slows down

dapper cobalt
#

Pretty useless.

slate swan
#

If you only use it once

dapper cobalt
#

And yes, slows down the process.

marble pilot
#

Yeah i know lol

slate swan
#

Just remove it, redundant stuff

marble pilot
#

ok

dapper cobalt
#
role = ctx.guild.get_role(role_id)
await ctx.author.add_roles(role)
#

Or

await ctx.author.add_roles(ctx.guild.get_role(role_id))
slate swan
#

xD

slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

Save it as a variable and then use .send() on it

#

heeelp

slate swan
#

Sorry but I don't quite understand, but using .join in a for loop is not really useful

#

idk what to do

slate swan
#

I'd say loop trough them, and append the counter and current link to a string

#

ok den

#

Because doing a loop and using .join is probably not what you want to do

waxen granite
#

hm

slate swan
#

You basically always overwrite

#

Because as you can see both URLs have \n\n{counter which is 2, so the last iteration}. in-between them

slate swan
#

Can i create a Discord Bot that records audio from voice channels and send it to a particular channel?

slate swan
#

What's the rate limit for rainbow role color? (ping me)

brisk fiber
#

they overload the api

slate swan
#

😒

#

But it's cool

#

It may be cool but it's bad

#

Β―\_(ツ)_/Β―

#

Kraots answer Gurudatta's question, I wanna know the answer πŸ™‚

slate swan
#

FUCK

#

But from what I've heard bots will get voice receiving in the future

slate swan
#

Idk when exactly since it's not really a topic that interests me

#

i thought i could make it w/ pypiwin32.

#

Nope, you can only do that on a user account

slate swan
#

Bots don't yet have the voice receive endpoint

slate swan
#

@<>discord plz add zaat zing ok?

slow cove
#

Anyone free to hop into a chat with me and help me out? Just started to dip my toe into the water of Python and am following freeCodeCamp's basic tutorial, but im hitting a snag

fallow mauve
#

lets say i want to test if someone has reacted to the bots message with a specific emoji and if they have then it deletes it, how would i do that?

main lotus
#

there is a specific function called on_reaction_add(reaction, user) but I think its for the bot

#

like the bot puts the reaction and user reacts to it

fallow mauve
#

thats what i want

#

but then what goes after that?

main lotus
#

alright

#

you can use if statement

#

like

#

if reaction.emoji == "some_emoji":

fallow mauve
#

ok

#

thx so much

main lotus
#

no problem

main lotus
fallow mauve
main lotus
#

only discord I suppose

#

gimme a sec

fallow mauve
#

it says undefined name "reaction"

main lotus
#

did you give reaction as a parameter?

fallow mauve
#

?

main lotus
#

something like this

fallow mauve
#

oh yeah i forgot, im testing it on an existing command so i forgot to do that

main lotus
#

no probs haha, it should work now

fallow mauve
#

atually it doesnt

#

*actually

main lotus
#

oh

fallow mauve
#

code:

@Bot.command()
async def test(ctx, reaction, user):
  await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
  await ctx.add_reaction(":EBright:")

  if reaction.emoji == ":EBright:":
    await ctx.edit("lol")

error:

Ignoring exception in command test:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await self.prepare(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: reaction is a required argument that is missing.
main lotus
#

right my bad I forgot to mention something

fallow mauve
#

ok

#

what

main lotus
#

so

#

for on_reaction_add to work
the bot itself will need to add reactions to a message
and then when the user reacts, then something will happen
I have tried to do with user simply adding the reaction for which a task is assigned to a bot
but it gave error

slow cove
#

like im just trying to get this to work, but they changed the command to tell the script what the OS key is so i followed that and i get just None in the output

#

Like... am i reading something wrong?

eager tapir
#

first wheres the token

fallow mauve
fallow mauve
slow cove
main lotus
#

ok so you have simply done ctx.add_reaction

#

you need to tell where

fallow mauve
#

so...

eager tapir
main lotus
#

so you will need a statement like

message = await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
await message.add_reaction(":EBright:")
fallow mauve
haughty sedge
#

yo

slow cove
haughty sedge
#

Halloween is coming!!

fallow mauve
main lotus
slow cove
#

thats what the client is

main lotus
#

just put client.run

fallow mauve
haughty sedge
#

oh wait wrong channel

fallow mauve
#

lol

haughty sedge
#

wait wrong server

main lotus
fallow mauve
#

lmao

slow cove
#

Im using Replit and they changed how that command works

#

yet when i do that, thats when i get the None message

main lotus
#

have you set it correctly?

#

None could be because TOKEN has no value

fallow mauve
#

did you make it a variable in the secrets tab?

slow cove
#

thats what gave me the big red spit out of dooooom

fallow mauve
slow cove
#

and yes its in the secrets as a variable

fallow mauve
#

this one

#

?

slow cove
#

eeeyup

fallow mauve
#

hmm

#

do you have the token right?

slow cove
#

Im pretty dang sure i do

fallow mauve
#

are all letters in the variable capitalized correctly

main lotus
#

well it would give key error or something if it didnt

slow cove
#

copied straight from the discord website

fallow mauve
#

hmm

#

idk

slow cove
main lotus
#

ahh

slow cove
#

Like unless im being a total boob head and have done a total blodie

main lotus
#

see the value box must have the token

#

not Hal

fallow mauve
#

you have the key and value switched

slow cove
#

OOOOOOOOOOOOOOOOOOOOOOOOOH MYYYYYYYYYYYYYYYYY GOOOOOOOOOOOOOOOOOOOOOOOOOD

fallow mauve
#

lol

slow cove
#

I

#

Am

#

an Idiot

main lotus
#

dw about it

#

I did the same thing once or twice too

#

xD

slow cove
#

Holy shit look at that, it works now!

main lotus
#

@fallow mauve did your command work?

main lotus
fallow mauve
#

error:

Ignoring exception in command test:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 855, in invoke
    await self.prepare(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: reaction is a required argument that is missing.
fallow mauve
#

code:

@Bot.command()
async def test(ctx, reaction, user):
  message = await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
  await message.add_reaction(":EBright:")

  if reaction.emoji == ":EBright:":
    await ctx.edit("lol")
main lotus
#

ok I think the problem is that

if reaction.emoji == "something" must be in on_reaction_add

#

and not in the command itself

#

so your command will have just one parameter ctx
and the on_reaction_add will have reaction and user

#

as parameter

fallow mauve
#

i dont get it

#

:/

main lotus
#

no probs

#

lemme arrange some stuff

#

gimme a sec

final iron
#

@slow cove you shouldn't really be using repl. It's a bad idea

fallow mauve
#

ive never used reactions for any of my bots yet so i have no idea how this works lol

slow cove
final iron
fallow mauve
#

?

main lotus
#
@Bot.event()
async def on_reaction_add(reaction, user):
  if reaction.emoji == ":EBright:":
    await reaction.message.delete(user) # not sure if its purge or delete :/
      
@Bot.command()
async def test(ctx, reaction, user):
  message = await ctx.send(":EBshapethink: :EBredthink: :EBbluethink:")
  await message.add_reaction(":EBright:")
#

this is something like it

final iron
#

Whats the message are you using to trigger the command

main lotus
main lotus
slow cove
main lotus
#

yeah

lapis lintel
#

Yes

main lotus
#

you could use powershell too. more or less the same as cmd

final iron
slow cove
#

well thats a whole kettle of fish ive got not idea how to do, like where would i store the key? would that be a file i make in notepad or sumtin?

#

now you guys got me doing the hacker stuff

main lotus
wintry shore
fallow mauve
#

i gtg eat lunch, b back in a few

main lotus
#

or you could just setup an environment variable file and then import dotenv
from there you can use load_dotenv to load that file and then os.getenv to get that variable

lapis lintel
slow cove
#

I am so lost, so for now, just to learn the basics i think ill stick to Replit, but ill defs look into that as a solution down the track

lapis lintel
#

At least that's what I used to do if I knew someone was going to see the code, or else i just put the token on the code

slow cove
#

When it comes to actually hosting the bot though, is it possible to host it locally and have it run off my machine instead of paying for a hosting site?

slow cove
#

Do forgive me ive literally had less than an hour experience at this πŸ˜„ πŸ˜„ πŸ˜„ πŸ˜„

brisk fiber
main lotus
lapis lintel
wintry shore
lapis lintel
main lotus
brisk fiber
lapis lintel
wintry shore
brisk fiber
#

that’s what i’m doing (hosting on a pi)

slow cove
main lotus
#

haha I was planning to setup a google cloud server for my bot
don't know much tho, its simply an idea

slow cove
#

Mine im making because a friend of mine made me one, was a ass hole to me, we had a fight, so out of spite she removed it. when my admins on my server use it QUITE FREQUENTLY

main lotus
#

also it reminds me
arduino? for hosting? possible?
would be cool for testing haha

slow cove
#

so now out of spite im teaching MYSELF python >:C

main lotus
#

dw you will get it eventually

slow cove
#

It seems pretty simple compared to other languages ive seen

#

and a lot of my mates that use it praise it's versatility

main lotus
#

python is easier compared to other langs haha

slow cove
#

so the bot im trying to make is one that generates a random single use invite code for my server which I can then provide to peeps joining it to prevent code spreading

main lotus
#

that's a nice idea

#

I wouldn't know though
I haven't explored that part of discord.py yet

slow cove
main lotus
#

stackoverflow

#

connect things, make shit haha

slow cove
main lotus
#

google it

slow cove
#

Okay ❀️

main lotus
#

Idk how to work with JSON yet πŸ˜… kinda clueless

slow cove
#

Well @main lotus . You have opened my eyes

#

Thank you @main lotus

main lotus
#

glad to be of help haha

lapis lintel
#

You can overwrite the welcome value, either to None, "", 0

waxen granite
wintry shore
slate swan
#

whats the best way to turn a .py file to a .exe

slate swan
final iron
slate swan
rare saddle
#

How to make a slash command for a discord bot with a cog system?

quasi pawn
#

How do I prevent the cooldown from triggering if the command encountered an error?

wintry shore
hasty iron
#

!d discord.ext.commands.Command.reset_cooldown

unkempt canyonBOT
quasi pawn
#

I see, thanks

rare saddle
#

What is the mistake, please tell me

lapis lintel
hasty iron
wraith bay
#

Γ±

hasty iron
#

oh wait nvm

lapis lintel
hasty iron
#

its the self.slash = … line that’s causing the error, you probably dont need it so remove it

waxen granite
rare saddle
lapis lintel
waxen granite
#

had to pop the key

#

welcome

dense swallow
#

a weird doubt, can u change the name of the bot role to a new one from dev portal?

waxen granite
#

yes

#

or wait

#

u mean one that is created when the bot joins the server?

#

if so, nope

inland wedge
#

Anyone has experience with python and replit i built a webscraping script and i used selenium and chromium for it, it worked past few days but today it suddenly stopped working, it endless loads the page and it says request timed out

dense swallow
#

I renamed my bot, so I wish to change the existing role name of bot

true horizon
#

how to create a command to check if a member has a certain role type 'if member.role == 'staff': ctx.send('Congratulations you are a staff')
else:
ctx.send('You are not a staff. Press F for more respect')

waxen granite
dense swallow
#

Then only it updates?

fallow mauve
#

it wont edit the message when i react

#

and theres no error

waxen granite
hasty iron
slate swan
#

Anyone tell me about encode ?

main lotus
#

ctx.channel.purge(limit=x) where x is some number

solid summit
slate swan
#

why

queen heart
#

Anyone can help me with python bot.

slate swan
#

.

queen heart
#

?

slate swan
#

yes

queen heart
#

Where can i paste my error?

manic wing
#

here

queen heart
#

ok

#

Ignoring exception in on_message Traceback (most recent call last): File \"/usr/local/lib/python3.9/site-packages/discord/client.py\", line 343, in _run_event await coro(*args, **kwargs) File \"/home/user_437283638976053249/main.py\", line 126, in on_message users = json.load(f) File \"/usr/local/lib/python3.9/json/__init__.py\", line 293, in load return loads(fp.read(), File \"/usr/local/lib/python3.9/json/__init__.py\", line 346, in loads return _default_decoder.decode(s) File \"/usr/local/lib/python3.9/json/decoder.py\", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File \"/usr/local/lib/python3.9/json/decoder.py\", line 355, in raw_decode raise JSONDecodeError(\"Expecting value\", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

manic wing
#

you need a {} in your json

slate swan
#

I'd like to start programming but I don't like that they use if instead of whenever

#

so I'm not gonna do that

queen heart
queen heart
true horizon
#

I can't create a permission check for the command could they help me?

slate swan
#

you can use @commands.has_role()

#

as a decorator

#

or use role = guild.get_role(id) first and then paste it in if role in mu.author.roles

true horizon
true horizon
broken dirge
#

div = soup.find("li", {"id": "randomword_1"}).get_text() div = div.strip() z = len(div) a = [ s[0] for s in div.split() ] x = 0 await ctx.send(f"{z} letters, first letter - **{a}** Ans.: {div}") while x < 3: def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel msg = await client.wait_for("message", check=check) intt = int(msg.content) if intt == div: await ctx.send("You won!") break elif intt != div: x += 1 await ctx.send("Try again!")

#

error: Command raised an exception: ValueError: invalid literal for int() with base 10:

#

maybe you guys know the solution

slate swan
#

why are you trying to cast the string msg.content into an int?

queen heart
shut axle
#
@client.command(aliases=['ctc'])
async def createtextchannel(ctx, channelName):
    await ctx.message.delete()
    guild = ctx.guild
    embed = discord.Embed(
        title='Success!',
        description='`{}` has been successfully created.'.format(channelName),
        color=discord.Color.green())
    if ctx.author.guild_permissions.manage_channels:
        await guild.create_text_channel(name='{}'.format(channelName))
        await ctx.send(embed=embed, delete_after=5)
    else:
        await ctx.send("{}, you are missing permissions.".format(
            ctx.author.name),
                       delete_after=5)

How can I create a voice channel from this command? What do I need to change?

queen heart
#

Idk

clear rapids
#

I want to host my discord bot online but all the services are paid , does anyone here knows about any free services where I can host my bot for free??
I tried replit but it shuts down after 1 hr

#

from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def home():
return 'Hello. I am alive!!'

def run():
app.run(host='0.0.0.0', port=8080)

def keep_alive():
t = Thread(target=run)
t.start() I'm using this on replit to keep my bot alive but it is also not working

clear rapids
reef shell
clear rapids
slate swan
#

That's what I'm doing

broken dirge
slate swan
#

Β―\_(ツ)_/Β―

reef shell
#

also heroku psql is cool , at least it's free

clear rapids
slate swan
#

Β―\_(ツ)_/Β―

reef shell
#

you need a vps for long run

slate swan
#

^

#

If you really want long run then you have to buy it

reef shell
#

and there are some cheap vps out there

slate swan
#

^

#

Like the host that @unkempt canyon is hosted on

#

Iirc it's hosted on linode

#

Ovh is yet another good and extremely cheap host

#

Β―\_(ツ)_/Β―

slate swan
#

but if he has built up a good logic, then yes

queen heart
#

i have this error idk why

 online!
Traceback (most recent call last):
  File \"/home/user_437283638976053249/main.py\", line 520, in \u003cmodule\u003e
    @slash.slash(description=\"Mostra a latΓͺncia de qualquer membro\")
NameError: name 'slash' is not defined```
clear rapids
queen heart
#

I use discord_slash

clear rapids
#

try name = ''

#

before description

queen heart
#

I use from discord_slash import SlashCommand

clear rapids
#

or name =none

queen heart
clear rapids
#

like this

#

@queen heart

queen heart
#

but why name= ""

#

Wait

shut axle
#

@clear rapids do you know how to make this code work as voice channel?

@client.command(aliases=['ctc'])
async def createtextchannel(ctx, channelName):
    await ctx.message.delete()
    guild = ctx.guild
    embed = discord.Embed(
        title='Success!',
        description='`{}` has been successfully created.'.format(channelName),
        color=discord.Color.green())
    if ctx.author.guild_permissions.manage_channels:
        await guild.create_text_channel(name='{}'.format(channelName))
        await ctx.send(embed=embed, delete_after=5)
    else:
        await ctx.send("{}, you are missing permissions.".format(
            ctx.author.name),
                       delete_after=5)
queen heart
#

Im dumbπŸ˜‚

#

Ty for the help

clear rapids
#

npπŸ˜‚

shut axle
#

k

lapis lintel
#

Are there any things I should do with my bot if i want to host it online rather than adding commands like

@client.command()
async def foo(ctx):
  print('Hello')
reef shell
#

hosting your bot has nothing to do with adding commands

lapis lintel
#

I've seen many python open source discord bots that and rarely they do simple stuff like commands and those things, they have these huge files where they connect and do bunch of things, is there something im missing that a public discord bot has to have?

clear rapids
lapis lintel
shut axle
# clear rapids have you tried guild.create_voice_channel

Like this?

@client.command(aliases=['cv'])
async def createvoice(ctx, channelName):
    await ctx.message.delete()
    guild = ctx.guild
    embed = discord.Embed(
        title='Success!',
        description='`{}` has been successfully created.'.format(channelName),
        color=discord.Color.green())
    if ctx.author.guild_permissions.manage_channels:
        await guild.create_voice_channel(name='{}'.format(channelName))
        await ctx.send(embed=embed, delete_after=5)
    else:
        await ctx.send("{}, you are missing permissions.".format(
            ctx.author.name),
                       delete_after=5)

#

channel*

reef shell
shut axle
#

guild = ctx.guild
nothing with that? @clear rapids

reef shell
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/master/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`VoiceChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceChannel "discord.VoiceChannel") instead.
clear rapids
#

async def cv(guild , channel_name , category_name = 'VOICECHANNEL',user_limit = 10):

reef shell
#

that's too much to do

clear rapids
#

and then await guild.create_text_channel(challen_name , category = category)

reef shell
#

you don't need the guild parameter

clear rapids
#

wait leme write full code

shut axle
#

ok

reef shell
#

as you can access it by Context.guild

shut axle
clear rapids
#

@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'VOICECHANNELS' , user_limit = '10'):
await ctx.message.delete()
guild = ctx.guild
embed = discord.Embed(
title='Success!',
description='{} has been successfully created.'.format(channelName),
color=discord.Color.green())
if ctx.author.guild_permissions.manage_channels:
category = get_category_by_name(guild , 'any category name in the channel')
await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
channel = get_channel_by_name = (guild , channel_name)
await ctx.send(embed=embed, delete_after=5)
return channel
else:
await ctx.send("{}, you are missing permissions.".format(
ctx.author.name),
delete_after=5)

#

try this @shut axle

shut axle
#

Okay

reef shell
clear rapids
#

I have edited it , I forgot to add voice

shut axle
#

Yeah

#

i see

broken dirge
#

Where do I place ous=True? dexcom = Dexcom("username", "password") # add ous=True if needed

reef shell
#

what?

#

what is this

clear rapids
#

ous?

broken dirge
#

I'm using dexcom API and I need to place ous=True

#

I just don't know where

reef shell
#

is this related to discord bots?

broken dirge
#

sorry!

clear rapids
reef shell
#

never heard about that tbh

broken dirge
broken dirge
clear rapids
shut axle
#

Nah

#

no errors

clear rapids
#

did you fix where I mistyped get as het?

shut axle
#

but I think it is related to

#
category = get_category_by_name(guild , 'any category name in the channel')
channel = get_channel_by_name = (guild , channel_name)
#

the get_category_by_name and get_channel_by_name

#

@clear rapids

clear rapids
#

no category is different

#

and channel name is the name of that voice channel

shut axle
#

But it is not working...

clear rapids
#

πŸ˜…

shut axle
#

??

clear rapids
#

hm nothin , I was just doing it roughly before

shut axle
#

.format(channel_name) *

#

fixed

#

for ya

#

But What should I do ?

clear rapids
#

hm send me the code that you are using now

shut axle
#
@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'VOICECHANNELS' , user_limit = '10'):
    await ctx.message.delete()
    guild = ctx.guild
    embed = discord.Embed(
        title='Success!',
        description='{} has been successfully created.'.format(channel_name),
        color=discord.Color.green())
    if ctx.author.guild_permissions.manage_channels:
        category = get_category_by_name(guild , 'VOICECHANNELS')
        await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
        channel = get_channel_by_name = (guild , channel_name)
        await ctx.send(embed=embed, delete_after=5)
        return channel
    else:
        await ctx.send("{}, you are missing permissions.".format(
            ctx.author.name),
                       delete_after=5) 
#

here it is @clear rapids

#

HUh

#

wait a minutes

#

NEVERMIND

#

it doesn't work /

clear rapids
#

wait a sec , did you changed the category_name??

#

to your bot test server's categories ?

shut axle
#

yes

clear rapids
#

oh okah

slim whale
#
@bot.command()
async def unban(ctx, members: commands.Greedy[discord.Member]):
    for member in members:
        await member.unban()
        await ctx.channel.send(f"He desbaneado a: {member.mention} del servidor!")```
#

why does this not unban?

shut axle
#

@clear rapids Any way to fix?

clear rapids
ripe jackal
#

add this

hasty iron
ripe jackal
#

somewhere

hasty iron
#

although be careful, the user converter can call the API

slim whale
slim whale
ripe jackal
#

mine is on top

slim whale
ripe jackal
#

yes

slim whale
#

okkk

#

thanks

ripe jackal
#

np, try and tell me if it works

slim whale
#

okk

slate swan
#

member would be in a guild

#

how do you wanna unban somebody from a guild

#

by getting him from the guild

slim whale
#

oh true

slate swan
#

that you wanna unban him from

ripe jackal
# slim whale okk
@client.command(aliases=['ub'])
@commands.has_permissions(ban_members=True)
async def unban(ctx,user:discord.User):
    guild=ctx.guild
    mbed=discord.Embed(title='Success!',description=f"{user} has been successfully unbanned!")
    await ctx.send(embed=mbed)
    await guild.unban(user=user)```
#

this is what i use

#

and on top the intents.members=True

slim whale
ripe jackal
#

oh, then I'm not sure

#

but make sure to add the intents thing

slim whale
hasty iron
#

i told you

#

if u don’t know what typehinting is and you’re literally doing it, you need to revisit your code or whatever

slate swan
#

wtf

slim whale
#

? wtf

#

Dont say this here wtf

slate swan
#

please leave?

slim whale
#

yes

#
@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, members: commands.Greedy[discord.Member]):
    for member in members:
        await guild.unban()
        await ctx.channel.send(f"He desbaneado a: {member.mention} del servidor!")```@hasty iron
slate swan
#

discord.User

slim whale
#

why? please dont discuss about this here.

slate swan
#

not discord.Member

slim whale
#

in async

slate swan
#

yes

slim whale
#
@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, members: commands.Greedy[discord.User]):
    for user in users:
        await guild.unban()
        await ctx.channel.send(f"He desbaneado a: {member.mention} del servidor!")```
slate swan
#

exactly

#

but

#

change the name of the list in async

#

to users

#

since this makes no sense

clear rapids
#

@shut axle

slim whale
#

users: commands

shut axle
#

?

clear rapids
#

def get_channel_by_name(guild , channel_name):
channel = None
for cnl in guild.channels:
if cnl.name == channel_name.lower():
channel = cnl
break
return channel

def get_category_by_name(guild , category_name):
channel = None
for cat in guild.categories:
if cat.name == category_name:
category = cat
break
return category

#

I forgot to tell you the def function

#

πŸ˜…

shut axle
#

Can you type it in a command?

clear rapids
#

wht?

shut axle
#

@clear rapids

slim whale
#

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'guild' is not defined @slate swan

slate swan
#

well lol

#

ctx.guild probably

slim whale
#

okk

clear rapids
hasty iron
#

!d discord.utils.find

unkempt canyonBOT
#

discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is β€˜Mighty’ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
slim whale
#

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unban() missing 1 required positional argument: 'user' now

#

@slate swan

slate swan
#

bru

slim whale
#

i put user in the ctx.guild.unban(user)

slate swan
slim whale
#

okk i try

clear rapids
#

I mean how to send it in a box?

shut axle
slate swan
#

send what

clear rapids
slim whale
#

```` py

` ```

clear rapids
#

oh okah

slim whale
#

like this without spaces

slate swan
#

<@&831776746206265384>

#

please

clear rapids
#
def get_channel_by_name(guild , channel_name):
    channel = None
    for cnl in guild.channels:
        if cnl.name == channel_name.lower():
            channel = cnl
            break
    return channel


def get_category_by_name(guild , category_name):
    category = None
    for cat in guild.categories:
        if cat.name == category_name:
            category = cat
            break
    return category


@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'VOICECHANNELS' , user_limit = '10'):
    await ctx.message.delete()
    guild = ctx.guild
    embed = discord.Embed(
        title='Success!',
        description='{} has been successfully created.'.format(channel_name),
        color=discord.Color.green())
    if ctx.author.guild_permissions.manage_channels:
        category = get_category_by_name(guild , 'Voice Channels')
        await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
        channel = get_channel_by_name(guild , channel_name)
        await ctx.send(embed=embed, delete_after=5)
        return channel
    else:
        await ctx.send("{}, you are missing permissions.".format(
            ctx.author.name),
                       delete_after=5) 
#

oh , thnx

hasty iron
#

pep8 is crying

clear rapids
slim whale
#

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10026): Unknown Ban @slate swan

sick birch
slate swan
#

what the

shut axle
#

because it has taken

slim whale
#

code is this py @bot.command() @commands.has_permissions(ban_members=True) async def unban(ctx, users: commands.Greedy[discord.User]): for user in users: await ctx.guild.unban(user) await ctx.channel.send(f"He desbaneado a: {user.mention} del servidor!")

sick birch
#
channel = discord.utils.get(guild.channels, name="channel-name")
slate swan
#

maybe the user you got is not banned?

slim whale
#

it is

#

i think (?)

hasty iron
#

discord said they aren’t

slim whale
#

i try it again

#

oh yea it works

#

thank u @slate swan <3

slate swan
#

hm

#

nice

clear rapids
#

now check if it works?

slate swan
#

I wonder what the next random shitpost is gonna be

shut axle
#

also channel = get_channel_by_name = (guild , channel_name)

remove the = after by_name

slate swan
#

!d discord.on_guild_role_create

unkempt canyonBOT
#

discord.on_guild_role_create(role)``````py

discord.on_guild_role_delete(role)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") creates or deletes a new [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

To get the guild it belongs to, use [`Role.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role.guild "discord.Role.guild").

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

!d discord.on_bulk_message_delete

slate swan
#

I feel bad for pinging mods

#

the guy instantly stopped right after

hasty iron
#

then you could’ve modmailed

thorn heart
#

Hey guys

pliant gulch
#

πŸ‘οΈ πŸ‘… πŸ‘οΈ

slate swan
#

wat

thorn heart
#

Could a command ignore arguments after alias?

hasty iron
thorn heart
#

example: /hi Anthony
would normally execute async def hi(ctx):

pliant gulch
#

You could've opened your PR after you fixed your type errors

hasty iron
#

i didn’t know they were there

#

pylance didnt warn me

clear rapids
pliant gulch
#

pylance uses pyright

#

not mypy

hasty iron
#

mypy sucks

#

now merge pr

thorn heart
#

ughm i wanted to create a command /ball . typical 8-ball command but it should ignore arguments

pliant gulch
#

No I haven't reviewed it yet blanket

thorn heart
#

just replying with some message

pliant gulch
hasty iron
#

so slow

#

ok

thorn heart
#

i ve done that already but i shouldve used (ctx, *, question) and it worked could i not use so much arguments that i dont actually use in def

pliant gulch
#

iirc, you don't need to have anything but ctx

#

discord.py will just ignore the extra words after the command, and the argument

thorn heart
#

nah i mean just ignore everythin after /ball

#

cuz last time i tried it it gives error

#

im not sure actually but

thorn heart
#

im new at python and bruh

pliant gulch
#

Try it Β―_(ツ)_/Β―

#

I remember it working like that

clear rapids
pliant gulch
paper bane
#

if you don't declare extra parameters other than ctx, it won't parse the extra arguments and ignore them

thorn heart
hasty iron
#

its just to make code cleaner

pliant gulch
#

wait what did you even link to

#

can you send the proper link

hasty iron
#

i just clicked a … on my review and clicked share

pliant gulch
#

Sends me to my comments

hasty iron
#

its in get_context

clear rapids
paper bane
#

ignore the extra arguments not the command itself

thorn heart
#

i mean ignore words after the command

pliant gulch
thorn heart
#

/ball Will Shawn eat rice in 20 minutes

clear rapids
#

oh I get it

thorn heart
#

SO it just runs async def ball(ctx)

hasty iron
pliant gulch
#

No I missed that comment

hasty iron
#

bruh

pliant gulch
#

I will change that yes

hasty iron
#

and also get_prefix still doesn’t check if its a coroutine function or not

clear rapids
hasty iron
shut axle
#

@clear rapids@clear rapids look

clear rapids
bright palm
shut axle
#
def get_channel_by_name(guild , channel_name):
    channel = None
    for cnl in guild.channels:
        if cnl.name == channel_name.lower():
            channel = cnl
            break
    return channel


def get_category_by_name(guild , category_name):
    category = None
    for cat in guild.categories:
        if cat.name == category_name:
            category = cat
            break
    return category


@client.command(aliases=['cv'])
async def createvoice(ctx, channel_name, guild , category_name = 'Voice Channels' , user_limit = 10):
    await ctx.message.delete()
    guild = ctx.guild
    embed = discord.Embed(
        title='Success!',
        description='{} has been successfully created.'.format(channel_name),
        color=discord.Color.green())
    if ctx.author.guild_permissions.manage_channels:
        category = get_category_by_name(guild , 'Voice Channels')
        await guild.create_voice_channel(channel_name , category = category , user_limit = user_limit)
        channel = get_channel_by_name(guild , channel_name)
        await ctx.send(embed=embed, delete_after=5)
        return channel
    else:
        await ctx.send("{}, you are missing permissions.".format(
            ctx.author.name),
                       delete_after=5)  

When I do: ?cv Voice Channels hello
it is create a voice channel called : Voice ...

#

@clear rapids %^^^^

clear rapids
#

it actually created a vc?

shut axle
#

Do you want to talk?

#

In a voice

pliant gulch
hasty iron
#

that’s way better now

harsh cradle
#

i have givelevel command and when i try it i get this:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "Context" failed for parameter "ctx".

pliant gulch
#

Right I need to add that

clear rapids
pliant gulch
clear rapids
shut axle
#

I will show ya..

#

I will speak

hasty iron
bright palm
clear rapids
hasty iron
#

also commands should be able to make multiple checks

pliant gulch
#

Yea, it does allow multiple checks

#

Internally checks append to a list

clear rapids
harsh cradle
pliant gulch
#

then in the handler it runs all

clear rapids
shut axle
#

Private

hasty iron
pliant gulch
#

I do

shut axle
#

On DM's

pliant gulch
#

what

hasty iron
#

huh

pliant gulch
#

I literally have a hasattr right there

hasty iron
#

thats for check

unkempt canyonBOT
#

lefi/exts/commands/core/command.py lines 21 to 23

if hasattr(self.callback, "check"):
    self.checks.append(self.callback.check)  # type: ignore```
hasty iron
#

and it just appends

#

if its a list you have to extend

clear rapids
harsh cradle
#

i have givelevel command and when i try it i get this:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "Context" failed for parameter "ctx".

pliant gulch
#

The deco returns the func, so you can keep adding on

clear rapids
pliant gulch
#

or do command lookup via name

pliant gulch
hasty iron
pliant gulch
#

Yea, I realized

pliant gulch
#

append as in making it a list

hasty iron
#

that’s what i was saying

pliant gulch
#

that's what i was saying

hasty iron
#

ok so

#

when you’re done do base class for ws

pliant gulch
#

I don't think I'm merging now

#

Since I don't even have "cogs"

#

Were calling them plugins, :^)

harsh cradle
#

guys pls

hasty iron
#

yoink nova’s idea

harsh cradle
#

help

pliant gulch
hasty iron
harsh cradle
# hasty iron just ask, dont ask to ask

i have givelevel command and when i try it i get this:
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "Context" failed for parameter "ctx".

hasty iron
#

code?

harsh cradle
# hasty iron code?
@bot.command()
async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
        if member == None:
            return
        if ctx.guild == None:
            return
        result = await self.find_or_insert_user(member)

        user_id, guild_id, xp, level = result
        print(xp, level)

        level = lvl
        
        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, level, user_id, guild_id))
        await self.db.commit()
        await ctx.send(f"{member.mention} level changed to {lvl}")
hasty iron
#

why do you have self

#

you do know what self is used for and when it’s used

harsh cradle
hasty iron
#

this is a cog?

harsh cradle
hasty iron
#

what?

harsh cradle
hasty iron
#

you seem to be confused on where self is used

#

do you actually know when we should add the self argument to a function?

slate swan
#
embed.footer += ""
``` this doesnt work because?
#

i want it to set as nothing

reef shell
#

This is empty by default

slate swan
#
@commands.Cog.listener()
    async def on_member_join(self, member):
        welcome_events = db.find_one({"guild_id": member.guild.id})["welcome-events"]
        chan = db.find_one({"guild_id": member.guild.id})["welcome_channel"]
        channel = self.bot.get_channel(chan)
        message = db.find_one({"guild_id": member.guild.id})["welcome_message"]
        title = db.find_one({"guild_id": member.guild.id})["welcome_title"]
        footer = db.find_one({"guild_id": member.guild.id})["welcome_message"]
        embed = discord.Embed(title="",description="",color=discord.Colour.from_rgb(255, 255, 255))

        if welcome_events is False:
            return
        if channel is None:
            return
        if message is None:
            embed.description += f"Welcome to {member.guild}!"
        if title is None:
            embed.title += ""
        if footer is None:
            embed.footer += ""
        else:
            embed.description += message
            embed.title += title
            embed.footer += footer
            await channel.send(embed=embed)
#

should i just do embed.footer == None?

#

dont feel like that would work

#

if footer is None:
pass

#

like this?

#

that makes sense lol idk why i didnt think of it

pliant gulch
#

No your thinking about this the wrong way,

#

You check if footer is not None, this is good

#

And if its none, that's where you run embed.set_footer

#

Otherwise if the footer is None it will not run set_footer and the embed will not have a footer

hollow agate
#
@client.command()
async def pickwinner(ctx):
    channel = client.get_channel(764581973044756501)
    msg = await channel.fetch_message(898309597104857128)
    ``` How could I make this command choose a random reaction from the defined message so they will win the giveaway?
slate swan
#
else:
            embed.description += f"{message}"
            embed.title += f"{title}"
            embed.footer += f"{footer}"
``` so do i need this
#

just forgot elif

cloud dawn
rapid whale
#
@commands.Cog.listener()
    async def on_member_update(self, ctx, member_before, member_after):
        nickname_after = f"{member_after.nickname}" if not member_after.nickname else member_after.nickname
        nickname_before = f"{member_before.nickname}" if not member_before.nickname else member_before.nickname
        embed = discord.Embed(timestamp = ctx.message.created_at , color = discord.Colour.random() ,
                              title = "Member Update")
        embed.add_field(name = "Nickname before:" , value = f"{nickname_before}" , inline = True)
        embed.add_field(name = "Nickname after:" , value = f"{nickname_after}" , inline = True)
        embed.set_thumbnail(url = f"{member_after.avatar.url}")
        embed.set_author(name = f"{self.osamu.user}" , icon_url = f"{self.osamu.avatar.url}")
        channel = self.osamu.get_channel(898199584726188042)
        return await channel.send(embed = embed)

So I've tried to make an event which allows me to log whenever someone's changing their nickname. However, the following error occures:

Ignoring exception in on_member_update
Traceback (most recent call last):
  File "/home/ohnezahn/.local/lib/python3.9/site-packages/discord/client.py", line 352, in _run_event
    await coro(*args, **kwargs)
TypeError: on_member_update() missing 1 required positional argument: 'member_after'
slate swan
#
welcome_events = db.find_one({"guild_id": member.guild.id})["welcome-events"]
        chan = db.find_one({"guild_id": member.guild.id})["welcome_channel"]
        channel = self.bot.get_channel(chan)
        message = db.find_one({"guild_id": member.guild.id})["welcome_message"]
        title = db.find_one({"guild_id": member.guild.id})["welcome_title"]
        footer = db.find_one({"guild_id": member.guild.id})["welcome_message"]
        embed = discord.Embed(title="",description="",color=discord.Colour.from_rgb(255, 255, 255))
        embed.set_author(name=f"{member.guild.name} | {member.guild.member_count} members",icon_url=member.avatar_url)

        if welcome_events is False:
            return
        elif channel is None:
            return
        elif message is None:
            embed.description += f"Welcome to {member.guild}!"
        elif title is not None:
            pass
        elif footer is not None:
            pass
        else:
            embed.description += message
            embed.title += title
``` it wont add the description
#

How to sandbox a cog?

hollow agate
#
@client.command()
async def pickwinner(ctx):
    channel = client.get_channel(764581973044756501)
    msg = await channel.fetch_message(898309597104857128)
    a = random.choice(msg.reactions)
    await ctx.channel.send(f'{a}')``` I think I'm close, currently it just sends the reaction how can I make it so it sends the random user's name?
fallow mauve
#

i need help w something, im trying to learn how to make an economy bot and its not working:
error:```
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "test" is not found

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

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

    @commands.command()
    async def test(self, ctx):
      await ctx.reply('Testing!')

def setup(bot):
  bot.add_cog(WorkCommand(bot))
slate swan
#
import discord
from discord.ext import commands
from pymongo import MongoClient


cluster = MongoClient("")
db = cluster["Feature"]["user_data"]

class EconomyCMDS(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    @commands.command()
    async def bal(self, ctx, member:discord.Member=None):
        member = ctx.author if not member else member        
        if member not in db.find_one({"user_id": member.id}):
                db.insert_one({
                    "user_id": member.id,
                    "bal": 0,
                    "bank": 0,
                    "inventory": [

                    ],
                    
                    
                })
                await ctx.reply("You have a balance of 0. Because you have just started using these commands")
        else:
            bal = db.find_one({"user_id": member.id})["bal"]
            bank = db.find_one({"user_id": member.id})["bank"]
            embed = discord.Embed(title="feature",description=f"`Balance:` **{bal}**\n`Bank:` **{bank}**")
            await ctx.reply(embed=embed)


def setup(bot):
    bot.add_cog(EconomyCMDS(bot))```
code ^^^
```py
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.econ' could not be loaded.
``` error ^^^
#

ExtensionNotFound

#

I know this but i cannot figure a way to fix it

slate swan
slate swan
#

Folder?

fallow mauve
slate swan
#

mhm

slate swan
#

for filename in os.listdir('./commands'):
if filename.endswith('.py') and not filename.startswith('_'):
bot.load_extension(f'cogs.{filename[:-3]}')
logging.info(f"loaded cog: {filename}")
ita already looking thru the folder

fallow mauve
slate swan
#

Agreed

#

maybe because it doesnt have the pycache folder?

#

No

#

Maybe set a name to the cog after the commands.Cog in the class definition

#

Because the code seems normal, at least I can't spot anything

#

Create a list and eventually save it in a database or a JSON file if it's not too big

#

Append to the list

#

Remove from the list

#

Use random.choice

#

That's basic Python knowledge

#

so frustrating

slate swan
#

just put that under self.bot = ?

#

list = []
x = "l"
list.append(l) maybe

slate swan
#

ohh i get what your saying

#

Have you learned Python before doing bots?

#

!resources

unkempt canyonBOT
#
Resources

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

slate swan
#

I'd learn Python before directly starting with a bot

#

And I wouldn't stayed on discord.js

slate swan
#

i need help, i am using cogs with discord.py, (note: this has been happening even since discord.py was abandonded) everytime i use the "help" built-in command it freaks out on me and sends so many help messages at once, been trying to fix it for a while but have zero idea whats going on

hardy yoke
# slate swan ```py welcome_events = db.find_one({"guild_id": member.guild.id})["welcome-event...

You should be using Motor not pymongo https://motor.readthedocs.io/
Pymongo is blocking, it'll stall your bot whenever it does anything which is obviously not ideal for a bot being used by multiple users at the same time
Motor is async and won't cause that problem.

try printing message and seeing what's in there. The code seems fine 2 me so it may be an issue with what's in the variable. Is there an error? Is the embed sending anything?

hardy yoke
slate swan
#

this has been on going for ever since i started

#

and its not only that, even if i remove the discord help and add my own named "help" it does the same

hardy yoke
slate swan
slate swan
hardy yoke
#

it can duplicate if you use it twice

slate swan
#

but why specifically with the use of "help"

#

everything else works fine

final iron
#

It's broken somehow

#

No idea how this managed to happen

fallow mauve
#

!d set

unkempt canyonBOT
#
set

class set([iterable])``````py

class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.

Sets can be created by several means:

β€’ Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`

β€’ Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`

β€’ Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
slate swan
#

is embed.description == "h" valid??

#

i'm trying to set the description based on a variable not add something to it

slate swan
final iron
slate swan
#

do what water_gazes said

final iron
slate swan
#

^^

#

anyone here know a good DB ?

sick birch
#

postgres

#

from what i've heard it's one of the best out there

slate swan
#

i see, i’ve used TinyDB before but never got it to go anywhere since my client backed out last second πŸ˜›

pliant gulch
#

Any database should be good

#

so as long as you use an async driver for it, as discord.py is an async environment

slate swan
hollow agate
#

So, I have a database setup. How could I make a mute command (with time) that persists over a restart?

I have no idea what I need to store, nor how I check if the time has extended the database time.

slate swan
#

discord.ext.commands.errors.ExtensionNotFound: Extension 'cogs.econ' could not be loaded.
what could be the causes of this

#
class EconomyCMDS(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    @commands.command()
    async def bal(self, ctx, member:discord.Member=None):
        member = ctx.author if not member else member        
        if member not in db.find_one({"user_id": member.id}):
                db.insert_one({
                    "user_id": member.id,
                    "bal": 0,
                    "bank": 0,
                    "inventory": [

                    ],
                    
                    
                })
                await ctx.reply("You have a balance of 0. Because you have just started using these commands")
        else:
            bal = db.find_one({"user_id": member.id})["bal"]
            bank = db.find_one({"user_id": member.id})["bank"]
            embed = discord.Embed(title="feature",description=f"`Balance:` **{bal}**\n`Bank:` **{bank}**")
            await ctx.reply(embed=embed)


def setup(bot):
    bot.add_cog(EconomyCMDS(bot))
``` thats the code in files with some imports obv
#

anyone got an idea when i do for member in ctx.guild.members with intents all on it only returns 9 members instead of the 70 members?

slate swan
fallow mauve
#

how do i whitelist a command for a user with a specific ID?

#

nvm

pliant gulch
slate swan
pliant gulch
#

I've been seeing a lot of shitty forks recently and bad attempts

#

So I decided to do it myself if I can't let others

slate swan
#

whats the issue im mad

#

fair enough

#

emojies wont work like they should

#

jesus christ

#
@client.command(aliases=["slots", "bet"])
@commands.cooldown(rate=1, per=3.0, type=commands.BucketType.user)
async def slot(ctx):
  """ Roll the slot machine """
  emojis = ":apple::tangerine::pear::lemon::watermelon::grapes::strawberry::cherries:"
  a = random.choice(emojis)
  b = random.choice(emojis)
  c = random.choice(emojis)

  slotmachine = f"[ {a} {b} {c} ]\n{ctx.author.name},"

  if (a == b == c):
    await ctx.send(f"{slotmachine} All matching, you won! :tada:")
  elif (a == b) or (a == c) or (b == c):
    await ctx.send(f"{slotmachine} 2 in a row, you won! :tada:")
  else:
    await ctx.send(f"{slotmachine} No match, you lost :cry:")
pliant gulch
#

Your emojis variable is just a string

#

Its not a list

slate swan
#

oh xD can u help

pliant gulch
#

Just turn emojis into a list

#

each emoji being an item of the list

slate swan
#

emojiList = ["emoji1", "emoji2"]

#

thx

#

obviously, replace the emoji1 and 2 with your own

fallow mauve
#

with a listen event, how do i make it detect whether the message is exactly as stated

slate swan
#

do you want just an exact message or a list of them?

fallow mauve
#

one exact

slate swan
#
#if u use cog
@commands.Cog.listener()
    async def on_message(self, message:discord.Message):
            if "string" in message.content:
                return
#if u dont ig use this idk LMAO
@bot.event
    async def on_message(message:discord.Message):
            if "string" in message.content:
                return
#

oops

fallow mauve
#

k

slate swan
#

something like that i guess?

fallow mauve
#

ill try it

slate swan
#

allright

fallow mauve
#

i think i found an easier way actually

#

im gonna stick with that cuz i gotta go eat dinner soon and i dont have time to figure other ways out rn

slate swan
#

allright

#

also i need help with it pinging the client

slate swan
#

hows that

slate swan
#

thx

#

<@USER_ID>

#

or <@!USER_ID>

#
  slotmachine = f"[ {a} {b} {c} ]\n{ctx.author.name},"
#

how would i do it im confused it doesnt work

stoic galleon
#

why do i get this error Ignoring exception in on_ready
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 43, in on_ready
if not db.find_one({"guild_id": server.id}):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/collection.py", line 1328, in find_one
for result in cursor.limit(-1):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/cursor.py", line 1238, in next
if len(self.__data) or self._refresh():
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/cursor.py", line 1130, in _refresh
self.__session = self.__collection.database.client._ensure_session()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1935, in _ensure_session
return self.__start_session(True, causal_consistency=False)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1883, in __start_session
server_session = self._get_server_session()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1921, in _get_server_session
return self._topology.get_server_session()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 520, in get_server_session
session_timeout = self._check_session_support()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 504, in _check_session_support
self._select_servers_loop(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 218, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 6168c65e5605563b88d1ebcb, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('vora-db-shard-00-00.jfhaw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('vora-db-shard-00-01.jfhaw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('vora-db-shard-00-02.jfhaw.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]>

slate swan
#

fr

#

something with your database is messing up

#

anyways

slate swan
#
slotmachine = f"[ {a} {b} {c} ]\n <@USER_ID>,"
pliant gulch
#

mmmmm, Implementing plugins is gonna be a pain

#

I gotta make a metaclass to wrap all methods

slate swan
slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'USER_ID' is not defined

#

xD

#

bruh

#

you have to get the users id

#

then replace the "user_id" with the users id

#

yeah, what he said