#discord-bots

1 messages · Page 487 of 1

river walrus
#

on_member_join(member)

slate swan
#

can u pass me a invite to ur server ?

river walrus
slate swan
#

not sure tbh

river walrus
slate swan
#

can someone help me how do i fix this?

slate swan
#

whats that?

#

hello, try this with sqlite3:

#

UPDATE member SET Pseudo = speedeux WHERE ID = 882348295710736424

#

and i got this:

#

sqlite3.OperationalError: no such column: speedeux

river walrus
slate swan
#

she exist

#
    (
    ID             int PRIMARY KEY UNIQUE,
    Pseudo          text,
    Balance         int DEFAULT 1000,
    Earned          int DEFAULT 0,
    Lost            int DEFAULT 0,
    Post            text DEFAULT 'Stagiaire',
    Experience      int DEFAULT 0,
    Salary          int DEFAULT 0,
    Composition     text DEFAULT '',
    ContributePoint int DEFAULT 0,
    Contribution    text DEFAULT '',
    ActyToday       int DEFAULT 0,
    ActyWeek        int DEFAULT 0,
    ActyMonth       int DEFAULT 0,
    Here            int DEFAULT 1
    )```
river walrus
#

Mb

#

You shouldn't have uppercase names btw

#

Sometimes it results into that

lament mesa
slate swan
#

can someone help me. how do i fix this?

uncut comet
#

hello how can i access my mongodb from a cog? do i need to setup a separate connection or is there a way to use the connection from the main bot file?

river walrus
lament mesa
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
uncut comet
slate swan
#

nobody gonna help me?

lament mesa
lament mesa
slate swan
lament mesa
slate swan
#
    print("name edit: ", new_name)
    cursor.execute("""UPDATE member SET Pseudo = {} WHERE ID = {}""".format(new_name, member_id))
    database.commit()```
#

the entire function

lament mesa
#

dont use .format

#

use query params

slate swan
#

with "?" ?

lament mesa
#

yeah

#
cursor.execute("""UPDATE member SET Pseudo = ? WHERE ID = ?""", (new_name, member_id))```
slate swan
#

ok thanks

river walrus
#

I love it

lament mesa
slate swan
lament mesa
lament mesa
#

oh

boreal ravine
#

Improper means wrong so regenarate your token.

slate swan
#

ok

#

i want to dm a user when they send a command like .check sfsdfdsfds
how do i do that?

river walrus
slate swan
#

ok

#

hi all

frail summit
#

hi

river walrus
slate swan
#

how many languages i can use to create discord bot?

#

like i can use c# to create discord bot

honest wing
#

Any language that has a discord libary lolo

frail summit
#

can anyone figure out which software is this

honest wing
#

Pycharm

slate swan
#

yeah

frail summit
#

ooh thanks a lot

#

it helped

slate swan
honest wing
#

I wouldn't recommend PyCharm ngl

slate swan
#

same

#

but i will

honest wing
#

Use atom or Visual Studio Code

slate swan
#

at some point

frail summit
#

Bro is Visual Studio Code better than pycharm

honest wing
honest wing
frail summit
#

ooh

lament mesa
slate swan
frail summit
#

but??

slate swan
#

for only for python development i highly recommend pycharm

frail summit
#

ooh ok

slate swan
#

if you are using any other languages and files too then vs code

slate swan
river walrus
slate swan
#

then why pycharm created 😄

uncut comet
#

how to use pymongo across a cog?

honest wing
lament mesa
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

honest wing
river walrus
honest wing
uncut comet
lament mesa
#

pycharm is very good for python

slate swan
honest wing
#

It's your personal choice.

river walrus
lament mesa
slate swan
honest wing
slate swan
#

see

#

i use vs code for python-dev because i use azure

#

otherwise i'll would be using pycharm

#

for highly level creating application

#

work matter , what are you doing

sly gorge
#

.

tulip smelt
#

hello i try to make a discord music bot and it give me this error (i am watch tutorial)

#

Python 3.8.2 (default, Feb 26 2020, 02:56:10)
run
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'run' is not defined
 ?play
File "<stdin>", line 1
?play
^
SyntaxError: invalid syntax
 run
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'run' is not defined

Replit: Updating package configuration

--> python3 -m poetry init --no-interaction

Ignoring exception in command play:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/Bomby/music.py", line 25, in play
ctx.voice_client.stop()
AttributeError: 'NoneType' object has no attribute 'stop'

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

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: AttributeError: 'NoneType' object has no attribute 'stop'

#

how can i solve it

#

this apper when i try to play something

tulip smelt
#

import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
def init(self, client):
self.client = client

@commands.command()
async def join(self,ctx):
    if ctx.author.voice is None:
        await ctx.send("You're not in a voice channel!")
    voice_channel = ctx.author.voice.channel
    if ctx.voice_client is None:
        await voice_channel.connect()
    else: 
        await ctx.voice_channel.move_to(voice_channel)

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

@commands.command()
async def play(self,ctx,url):
    ctx.voice_client.stop()
    FFMPEG_OPTIONS = {'before_obtions': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    YDL_OPTIONS = {'format':"bestaudio"}
    vc = ctx.voice_client

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
       info = ydl.extract_info(url, download=False)
       url2 = info['formats'] [0] ['url']
       source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
       vc.play(source)

@commands.command()
async def pause(self,ctx,url):
    await ctx.voice_client.pause()
    await ctx.send("Paused")

@commands.command()
async def resume(self,ctx,url):
    await ctx.voice_client.resume()
    await ctx.send("resume")

def setup(client):
client.add_cog(music(client)) @river walrus

tidal hawk
#

Can somebody suggest me, how to create a command, which can user only use once a day.

#

like ".daily"

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

slate swan
#

!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)
maiden fable
#

!paste (sorry)

#

https://paste.pythondiscord.com/urusizunah.py

When I click the NextButton, it prints 2 and then 1, but when I click PrevButton, it prints 1 and then errors out... It is not setting the page as 2, thus returning a KeyError that the key 0 isn't in the dict... How to fix it?

tulip smelt
#

@river walrus if you want i cant screen share and explain what i try and what i do better

spring flax
#

Hunter

maiden fable
#

Hi

spring flax
#

You should know that

#

Error is helpful

maiden fable
#

pithink Just a KeyError that 0 isn't there in the dict

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

maiden fable
#

because the page var isn't set to 2 on press idk why

tidal hawk
#

Can somebody suggest me, how to create a command, which can user only use once a day.
like ".daily"

maiden fable
#

There, edited the message

maiden fable
#

Wait, nvm

#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
slate swan
#

cooldown

tidal hawk
#

thanks :*

slate swan
#

doesn't it take a check?

maiden fable
#

Yea by mistake read it as How to make something run once everyday

maiden fable
tidal hawk
#

np

maiden fable
#

BTW @spring flax any idea?

spring flax
#

yes one second looking at the code

maiden fable
#

Well my understanding is that it isn't updating the original class's page var

#

Cool

patent perch
#

Can I get help here?

maiden fable
#

Yea

patent perch
#

Cool

spring flax
#

also, may I ask why you aren't using dpy's buttons?

reef shell
spring flax
#

that's what you want right

maiden fable
#

Yea....?

#

I mean, I am using disnake

reef shell
#
async def interaction_check(self, intr):
    return #idk how to do this.. maybe ctx.author == intr.author?```
how to check if the user interacting is the author ?
maiden fable
#

u need another arg in the init

#

from a command

reef shell
#

self.ctx?

maiden fable
#

and then check self.inter.author == inter.author

reef shell
#

oh

#

alr

patent perch
# reef shell sure, lol

I want to be able to have a kind of money system for each server and I want verified purchases stored in a json file. Would anyone know how I can get the value of a certain object by serverID?

{
    "ServerID": {"Purchase1": 1, "Purchase2": 0, "Purchase3": 1}
}```
Currently, I've unsuccessfully tried using this:
```python
def check_purchase(client, message, purchase):
    try:
        with open('json/Purchases.json', 'r') as f:
            purchases = json.load(f)
            return purchases[str(message.guild.id)]
        
    except:
        return '0'```
#

Sorry for ping, I meant to turn that off.

slate swan
#

that's no dpy relation

reef shell
maiden fable
#

Hey @slate swan mind looking at the code?

reef shell
#

and i'm not so familiar with that

patent perch
slate swan
#

I can

reef shell
tulip smelt
#

@river walrus sry bro i am so dumb can you try to explain me what i do wrong is my first time codeing in python

maiden fable
slate swan
maiden fable
reef shell
#

replit is bad,

slate swan
#

oh shit that's advanced af

river walrus
patent perch
reef shell
slate swan
#

Getting an error while running this code:

async def embed_func(ctx):
    embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
    embedVar.add_field(name="** **", value=":emoji_1: :emoji_1:", inline=False)
    embed = await ctx.send(embed=embedVar)
    await asyncio.sleep(1)
    embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
    embedVar.add_field(name="** **", value=":emoji_4: :emoji_2:", inline=False)
    embed.edit(embed=embedVar)
    await asyncio.sleep(1)
    embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
    embedVar.add_field(name="** **", value=":emoji_3: :emoji_1:", inline=False)
    embed.edit(embed=embedVar)
    await asyncio.sleep(1)
    embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
    embedVar.add_field(name="** **", value=":emoji_4: :emoji_4:", inline=False)
    embed.edit(embed=embedVar)
    await asyncio.sleep(1)
    embedVar = discord.Embed(title="Snake Eyes", color=0x2C5ED1)
    embedVar.add_field(name="** **", value=":emoji_3: :emoji_2:", inline=False)
    embed.edit(embed=embedVar)
    await bot.delete_message(embed)

embed_func()

The error says something like "embed_func missing one positional argument named ctx")

maiden fable
reef shell
tulip smelt
#

@river walrus oh i not knowing that this is how the man from the tutorial saw how to make a music bot

slate swan
#

it's legit telling u what u did wrong

river walrus
patent perch
river walrus
#

They suck

slate swan
#

why does he teach breaking YT ToS on YouTube

#

what the fuck

tulip smelt
#

@river walrus thx for tips and have a nice day

slate swan
slate swan
#

yes

#

if it's inside a command

#

Alright, thanks!

river walrus
slate swan
#

I can't even look at hunter's code without getting blind

#

I'm too weak for that

maiden fable
#

Yo @spring flax got anything in mind? I have been brainstorming this since like 30 min

maiden fable
slate swan
#

nah, it probably ain't

maiden fable
#
    self.paginator.paginator_embed.description = "\n".join(f"{key}: {value}" for key, value in self.paginator.paginator_dict[self.paginator.page])
KeyError: 0
slate swan
#

I'm too meh

slate swan
maiden fable
slate swan
#

Oh it isn't a command, just a function @river walrus

#

no documentation for 2.0

#

I'm dying

maiden fable
#

Lol

slate swan
#

how would I even learn it like that NotLikeThis

stone palm
#

h-h-hi h-h-hunter

spring flax
maiden fable
#

and the reason is cz the page variable isn't getting set to 2 when the NextButton is clicked

#

I just don't know how to fix it

spring flax
#

this is for prevbutton?

maiden fable
#

The error? Yea

spring flax
#

what is self.paginator_page?

#

the value of it

maiden fable
#

u mean self.paginator.page?

spring flax
#

yeah

maiden fable
#

When I click the NextButton then

1
2

after that, when I click the PrevButton

1
KeyError 0
#

So that tells me the value isn't updated

spring flax
#

what's self.paginator.page though

maiden fable
#

The current page number

spring flax
#

did you just do like self.paginator.page = 1?

maiden fable
spring flax
#

uhh sorry can't see why it's happening

maiden fable
#

:c

#

I was thinking this was gonna be easy pithink

#

Breh I will have to use globals

#

I don't want to use them :c

craggy cloak
maiden fable
#

pip install discord.py[voice]

craggy cloak
maiden fable
#

Well I think I have found a way, time to try it

lofty mulch
#

TypeError: __init__() missing 1 required positional argument: 'bot'

#

any hints on this?

slate swan
#

you didn't pass bot when you instantiated the class

lofty mulch
#

Thing is, it's not even inside a class

slate swan
#

then where

lofty mulch
#

Wait

#
async def main():
    Bot = CogManager()
    await Bot.start(Token)
#

I still have to pass bot?

slate swan
#

show where u defined CogManager

lofty mulch
#

In the same file as this one

river walrus
slate swan
#

i only need to see the __init__ of it

lofty mulch
#
class CogManager(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    @watch(path='Cogs')
    async def on_ready(self):
        print ('Bot is ready.')

    async def on_message(self, message):
        if message.author.bot:
            return

        await self.process.command(message)


# Starting 

async def main(bot):
    Bot = CogManager()
    await Bot.start(Token)

if __name__ == '__main__':
    asyncio.run(main())```
lofty mulch
#

It's more of a habit

lofty mulch
#

Yep, i'm trying out cogwatch

slate swan
#

u don't even have a start method in your class

lofty mulch
#

No idea of what I'm doing

slate swan
#

1st, you're subclassing Cog and assigning CogManager to a Bot variable, which makes no sense

2nd, since it's not a subclass of Bot, you don't have the .start method

3rd, why are you using asyncio.run to run your bot when that's done automatically by the lib

4th, your __init__ takes bot as the param, so when you do CogManager() you need to pass bot

silk mauve
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice

slate swan
#

install pynacl

#

pip install PyNaCl

silk mauve
#

Alr

lofty mulch
slate swan
silk mauve
# slate swan `pip install PyNaCl`

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice

#

Still.

slate swan
#

bruh

#

did u install it

lofty mulch
#

I'm literally copying it because I'm trying to understand what even is it

silk mauve
#

ye

lofty mulch
#

And why not?

slate swan
lofty mulch
#

Can't exactly understand something without trying it out

slate swan
lofty mulch
#

That's pretty much how I learn things, trying out

slate swan
silk mauve
#

Doesnt

slate swan
slate swan
steel oasis
#

how to change status of discord bot like change it to don't disturb

silk mauve
#

cmd

slate swan
unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter.
steel oasis
slate swan
lofty mulch
silk mauve
#

Wait

#

I will restart

lofty mulch
#

Pretty much testing

slate swan
#

alr

silk mauve
#

Worked, ty

slate swan
#

yw

slate swan
# lofty mulch Pretty much testing

but please at least have some basic knowledge before doing so, the code you just sent is completely broken and you should've noticed at least that

lofty mulch
#

Well, fair enough I guess

#

Well, back to the forums I go

slate swan
#

lmao

#

¯_(ツ)_/¯

steel oasis
#

my code isn't even running and my bot works

#

wtf

slate swan
steel oasis
lofty mulch
#

Bot's literally too angry to die

hasty iron
#

then dont use replit

silk mauve
steel oasis
silk mauve
#

Bc it shows an error

steel oasis
#

Finally it died

lofty mulch
#

Turns out it wasn't too angry to die

steel oasis
#

any good hosting service 24/7 that doesn't require me to have a webpage open?

slate swan
silk mauve
#

ty

steel oasis
slate swan
#

vps = virtual private server

steel oasis
#

how to make that?

#

lemme google

slate swan
#

there

steel oasis
#

jk

slate swan
#

those are some good vps

steel oasis
#

yes but how to use them?

slate swan
#

idk never used one

steel oasis
#

literally none of the pages work

#

404 erro or smthn

slate swan
#

bro read the error it's basic error

steel oasis
#

where are you puttin it in ur code?

silk mauve
#

I see

steel oasis
#

send code

hasty iron
#

await needs to be inside an async function

steel oasis
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

hasty iron
slate swan
#

hmm understandable

#

how do i put continue it keeps saying 'continue is not properly in loop'

 if "jpg" not in url or "png" not in url:
        continue
maiden fable
#

Yo @spring flax (sorry for the ping), but the paginator is now working perfectly... I was just overcomplicating things for no fking reason

steel oasis
#
import discord

import os

client = discord.Client()

token = "HALL NO, YOU DON'T GET MA TOKEN"

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game('With Team Lunar'))
    
    await client.change_presence(status=discord.Status.dnd), await client.change_presence(activity=discord.Game('With Team Lunar'))
    
    print('Connected to bot: {}'.format(client.user.name))
    
    print('Bot ID: {}'.format(client.user.id))


client.run(token, bot=True)

doesn't show don't disturb only playing with team lunar

hasty iron
#

continue only works in for and while loops

slate swan
upbeat blaze
upbeat blaze
dapper cobalt
#

Each one of the 3 is different than the others.

#

!d discord.ext.commands.Bot.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter.
steel oasis
#

hmm

#

so like this

@client.event
async def on_ready():
   await client.change_presence(activity=discord.Game("with team lunar"), status=discord.Status.dnd)
    
    print('Connected to bot: {}'.format(client.user.name))
    
    print('Bot ID: {}'.format(client.user.id))

@dapper cobalt

steel oasis
dapper cobalt
#

What is it?

#

!d discord.Game

unkempt canyonBOT
#

class discord.Game(name, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that represents a Discord game.

This is typically displayed via **Playing** on the official Discord client.

x == y Checks if two games are equal.

x != y Checks if two games are not equal.

hash(x) Returns the game’s hash.

str(x) Returns the game’s name.
steel oasis
#
  File "main.py", line 13
    print('Connected to bot: {}'.format(client.user.name))
    ^
IndentationError: unexpected indent
dapper cobalt
#

Indentation error.

steel oasis
#

I don't know what indetation means sorry I am new to coding

#

and english is not my first langauage

#

@dapper cobalt

dapper cobalt
#

You should learn basics of Python before making a Discord bot.

steel oasis
#

I am doing so

slate swan
#

Indentation is the tabs and spaces before words

#

Like if you had an if statement, the indentation would be like this most likely:

If x == y
Print("rawr")

hasty iron
#

if you dont know what indents are, learn more python

#

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

Could be a translation issue, said his first language isn't English

hasty iron
#

when you code 90% of the time it’s going to be english

gritty flame
#

or twice

pliant gulch
#

4 spaces and one tab is not the same

#

Its just that your IDE turns tabs into spaces, usually 4

lofty mulch
#

@slate swan Incredible

slate swan
#

?

lofty mulch
#

I've been googling for like

#

20 mins

#

and I couldn't find anything significant on cogwatch

slate swan
#

¯_(ツ)_/¯

lofty mulch
#

Shit's scarce

#

Back to bot.reload_extension we go

slate swan
#

😂

tidal hawk
#

can i see how many seconds are left for cooldown end?

#

with CommandsOnCooldown error

hasty iron
#

!d discord.ext.commands.CommandOnCooldown.retry_after

unkempt canyonBOT
tidal hawk
#

hm

#

thanks

slate swan
#

and in on_ready aswell

reef shell
#

anyone knows how to disable a button when the button was created using ui.button deco.?

#

I mean how do i get that button object?

pliant gulch
#

The callback, which is the function you decorate with that decorator has access to the button param which should be the first one

hasty iron
#

the button object gets passed in as a parameter

pliant gulch
#

This will be the corresponding button

quiet coral
#

hello,what are some of the best resources to learn to code discord bots?

reef shell
#

button.disabled = True?

#

I tried this but doesn't work

pliant gulch
#

Hmm should've worked, maybe you are doing something wrong not sure

unkempt canyonBOT
#

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

ServerDisconnectedError: Server disconnected

final iron
#

Uh oh

flat solstice
#

I'd need to use await self.bot.fetch_channel right? laws = await fetch_channel(287435156720058370)

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

crystal cliff
river walrus
crystal cliff
river walrus
#

Not yet implemented

#

But we will

#

For sure

crystal cliff
#

buttons?

river walrus
#

Lemme try to find a good example

crystal cliff
#

dm me, when you start it, im interested, in what it does 🤔

river walrus
crystal cliff
#

g2g 👋

river walrus
#

Aight

pliant gulch
woeful fable
#

would anyone take a look at my code and try to figure out whats wrong?

pliant gulch
# pliant gulch Just looked at the `client.py` for your lib, I think its very messy imo and coul...

For an example, heres my early implementation for my own lib that I started a while back ```py
from future import annotations

import typing
import inspect

import asyncio

from .http import HTTPClient
from .ws import WebSocketClient

all = ("Client",)

class Client:
def init(
self, token: str, loop: typing.Optional[asyncio.AbstractEventLoop] = None
):
self.loop: asyncio.AbstractEventLoop = loop or asyncio.get_event_loop()
self.http: HTTPClient = HTTPClient(token, self.loop)
self.ws: WebSocketClient = WebSocketClient(self)

    self.events: typing.Dict[str, typing.List[typing.Callable]] = {}


def add_listener(self, func: typing.Callable, event_name: typing.Optional[str]):
    name = event_name or func.__name__
    if not inspect.iscoroutinefunction(func):
        raise TypeError("Callback must be a coroutine")


    if name in self.events:
        self.events[name].append(func)
    self.events[name] = [func]


def on(
    self, event_name: typing.Optional[str] = None
) -> typing.Callable[..., typing.Callable]:
    def inner(func: typing.Callable) -> typing.Callable:
        self.add_listener(func, event_name)
        return func


    return inner


async def connect(self) -> None:
    await self.ws.start()


async def login(self, token: str) -> None:
    await self.http.login(token)


async def start(self) -> None:
    await asyncio.gather(self.login(self.http.token), self.connect())
#

Everything is neat and organized, I think you should clean your's up as it will make it easier to read

quiet coral
pliant gulch
hasty iron
#

oh

unkempt canyonBOT
#

discord/client.py lines 1 to 8

from logging import Handler
import handler
import websocket
import aiohttp
import intents as intent
from os import getenv
import typing
import asyncio```
pliant gulch
#

And is there a reason why you do getenv? Library shouldn't be handling that, rather the user does

#

Seems out of scope

wispy spade
#

*although the client i made for the api is probably messier

pliant gulch
#

I'm probably judging to much, I just like writing really clean code so

hasty iron
#

and why is loop a private attribute

#

if you really dont want people to change it, make it a read-only property

pliant gulch
hasty iron
#

wouldnt this error import websocket i think it should be from . import websocket

wispy spade
unkempt canyonBOT
#

discord/client.py lines 70 to 76

async def handle_event(self, msg):
    event = msg['t']
    try:
        for coro in self.events[event]:
            await coro(msg)
    except KeyError:
        return```
pliant gulch
#

whats dispatch code doing in client?

#

Shouldn't that be placed in websockets

wispy spade
river walrus
unkempt canyonBOT
#

discord/websocket.py lines 43 to 48

def keepAlive(self) -> None:
    while True:
        time.sleep(self.hb_int)
        asyncio.run(self.heartbeat())

def on_websocket_message(self, msg: dict) -> dict:```
pliant gulch
#

camel case then snake case?

#

And why are you using threading? If you did what I did in my example for websockets that stays alive

#

No need for threading

river walrus
hasty iron
#

if we ignore most stuff there then it would be a decent lib

#

also why, just why? asyncio.run and time.sleep

wispy spade
pliant gulch
#

Just leave the method in websockets lol

#

seems out of place and the name doesn't make sense

pliant gulch
pliant gulch
#

I'm just picky when it comes to clean code/unclean

hasty iron
#

rn it definitely needs a whole rewrite

wispy spade
pliant gulch
#

Inspiration from discord.py is always fine as well, as visible but sometimes its better to make your own impl

river walrus
pliant gulch
#

Just left it in websockets, kept the client void of any websocket stuff

river walrus
hasty iron
#

it doesn’t really matter who knows the API but what matters is how you implement it

quiet coral
#

beginner question how do I make my bot go offline with discord.py?

wispy spade
hasty iron
#

but if they do it properly or not is a whole other matter

wicked atlas
unkempt canyonBOT
#

discord/handler.py line 10

self.user_agent: str = "Disthon test library V0.0.1b. User: sebkuip#3632"```
wicked atlas
pliant gulch
hasty iron
#

yeah

hasty iron
#

lol user agent, i don’t even use one

pliant gulch
#

same

wicked atlas
#

Honestly it is a bit weird they say "must provide a valid User Agent" if they don't even check it or dish out punishment for not using it

wispy spade
wicked atlas
#

Well, if you're going to have a user agent, should at least be a good one

river walrus
flat solstice
#

Is there any way to get member/user info from a DM failure HTTP exception? i.e the name of the user who caused the exception

wicked atlas
wispy spade
slate swan
#

to make it appear offline

#

!d discord.Status.invisible

unkempt canyonBOT
river walrus
hasty iron
#

how different is it

quiet coral
slate swan
#

no

#

np*

flat solstice
flat solstice
night crater
#

nope, discord doesnt give this at all

reef shell
flat solstice
flat solstice
night crater
#

also if the member is a bot

#

you'll get Forbidden iirc

reef shell
#
@discord.ui.button(label="Page 1", style=discord.ButtonStyle.green)
    async def page_one(self, button: discord.ui.Button, interaction: discord.Interaction):
        

        await interaction.message.edit(embed=self.page1)
        button.disabled = True
        ```
the button is not getiing disabled , also I'm getting no error message in terminal
#

any solutions?

night crater
#

mmm my first guess is you probably need to do it before editing

#

otherwise I dont see where Discord is going to be told to update otherwise

reef shell
#

also tried that

night crater
reef shell
#

oh

slate swan
#
a = (response.json()['phone'])
            payload = {
                "phone": a, 
                "Content-Type": "application/json",
            }

            headers2 = {
                "Authorization": r.json()["token"],
                "user-agent": "Mozilla/5.0 (Windows NT 10.0;                 Win64; x64) AppleWebKit/537.36 (KHTML, like                  Gecko) Chrome/93.0.4577.82 Safari/537.36"
            }

            r2 = requests.post('https://discord.com/api/v9/users/@me/phone', json=payload, headers=headers2)
            print(r2.text)

heres my issue, im pretty much trying to send a request to verify my discord account through phone number

and for some reaosn when i generate the phone number it comes like +7865754864 with the country code at the beginning of it, then when i send that with the request, it says invalid phone number, i tried removing the +7 but it said invalid because the box where you select the country needs to be +7, and its default is +1, i dont know if i could change the language of the account, or something. idk if this is gonna make sense

btw im not using this for malcious purposes, just to let you know, im legit testing networking since im trying to become better at python and this thing wont work

please read all

night crater
#

that'll get you banned from Discord for doing that

#

because that's essentially self boting / automating the API

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

final iron
#

Is there a built in function in discord.py to create an invite for your bot or would I have to do it another way?

night crater
#

i mean you can use the developer portal

final iron
#

Yeah but I was thinking of making a command

night crater
#

https://discord.com/developers/applications/<bot id>/oauth2

final iron
#

Oh

night crater
#

thats the link to the webpage btw

final iron
#

ty

night crater
#

not the link to invite it

final iron
#

I honestly didn't think of that

#

Yeah ik

slate swan
#

how can i make a loop command for music

final iron
final iron
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)
slate swan
#

and what could happen to me?

slate solar
#

i need help in this
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(member.guilds)} members"))
i want it to be like it

slate solar
#

can you give me plz?

valid niche
slate swan
#

@client.event
async def on_ready():
print('Bot online')

servers = len(client.guilds)
members = 0
for guild in client.guilds:
    members += guild.member_count - 1

await client.change_presence(activity = discord.Activity(
    type = discord.ActivityType.watching,
    name = f'{members}'
))

Should work

valid niche
#

so you just set the rest of the text how you like it

slate solar
#

i know

#

i want the member count

slate swan
#

oh

#

add

final iron
slate swan
valid niche
valid niche
#

think a few thousand to a few tens of thousands of dollars

full lily
#

well.. unlikely

slate solar
#

can you send me that in the code?

valid niche
wicked atlas
valid niche
wicked atlas
#

Well, yeah, if you're downloading copyrighted content

valid niche
#

which most are

#

or allow the users to look for copyrighted material

full lily
#

tos is legally binding

wicked atlas
#

Yeah, guess if you put it that way

uncut comet
#

hey how can i call a subroutine through a cog?

full lily
uncut comet
#

on the main python code be able to call and run a subroutine thats in a different python file

flat solstice
#

Is this the correct way to handle the errors of events inside of a cog? I have a on_member_join event which can error when the bot tries to dm a member with closed DMs and I want the bot to send a msg to a channel when/if such a error occurs but I'm evidently not doing it right as it's not sending my msg but i don't know where I'm going wrong.py async def on_error(self, ctx, error): if isinstance(error, discord.HTTPException): if error.code == 50007: fail = await self.bot.fetch_channel(816480968830353458) # Your ID: self.bot.config.code_of_laws await fail.send(embed = error_embed(colour = self.bot.error_colour, description = f"I was unable to DM {ctx.author}, It appears this user has their DMs closed. Get them to check their *Allow direct messages from server mebers* setting under **Privacy and Safety**. I advise reaching out to this user yourself."))

full lily
#

do you have the event decorator above the func there?

flat solstice
#

nope

full lily
#

well there's your problem

flat solstice
#

that would be? never really touched error handlers b4

night crater
full lily
#

on_error is an event, so you wanna put @bot.event above that func there

valid niche
#

so it's cog.listener

full lily
#

in that case

flat solstice
full lily
#

^^

night crater
uncut comet
#

ok thanks

night crater
#

Oh the joys of slash commands

uncut comet
flat solstice
# full lily `on_error` is an event, so you wanna put `@bot.event` above that func there

okay so I have thispy @commands.Cog.listener() async def on_error(self, ctx, error): if isinstance(error, discord.HTTPException): if error.code == 50007: fail = await self.bot.fetch_channel(816480968830353458) # Your ID: self.bot.config.code_of_laws await fail.send(embed = error_embed(colour = self.bot.error_colour, description = f"I was unable to DM {ctx.author}, It appears this user has their DMs closed. Get them to check their *Allow direct messages from server mebers* setting under **Privacy and Safety**. I advise reaching out to this user yourself."))which to my understanding should work, except it's not sending the msg and I think it's getting stuck on the discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user which is the evnt it's supposed to be responding to

night crater
night crater
#

also make sure that the error hasn't been propagated up and has an original attribute which contains the original error.
This tends to be why you see alot of error handler code having error = getattr(error, 'original' error)

inland venture
#

whats a good combination of thunerz and python
im trynna name my bot

uncut comet
night crater
#

which returns either the instance or None (if the cog doesnt exist)

night crater
#

not that it matters much

flat solstice
# night crater you should really be checking if it's `discord.Forbidden` instead of checking i...

okay well I changed it to thispy @commands.Cog.listener() async def on_error(self, ctx, error): #error = getattr(error, 'original' error) if isinstance(error, discord.Forbidden): if error.code == 50007: fail = await self.bot.fetch_channel(816480968830353458) # Your ID: self.bot.config.code_of_laws await fail.send(embed = error_embed(colour = self.bot.error_colour, description = f"I was unable to DM {ctx.author}, It appears this user has their DMs closed. Get them to check their *Allow direct messages from server mebers* setting under **Privacy and Safety**. I advise reaching out to this user yourself."))Reason I'm checking the code is because as far as I am aware only DM failures cause 5007 and I want to only get those, if other stuff happens to be in it then fine but I want to minimise that. I tried that error = getattr(error, 'original' error) bit i obviously wsn't using to right bc it just gave me syntax errors

night crater
#

you missed a comma off the end of 'original'

#

sorry that was my bad 😅

#

also make sure another listener isn't consuming and silencing the error already

flat solstice
#

and if so then I just check the error code in that handler and pass it right?

night crater
#

you can do that yes

#

but yes error handlers can and will affect each other if you dont re-raise / consume them

unkempt canyonBOT
valid niche
#

it just makes less possible and they are tedious to work with

night crater
#

I mean you need a decent framework for them to suck less

#

but they can be pretty neeto at times

valid niche
#

the only upside i really see to it is that it makes it easier for users to correctly input everything

#

outside of that i don't see a single benefit

flat solstice
# night crater you can do that yes

okay so i think the other handler is still consuming it unfortunately so i'm gonna call it a day bc it's getting late and come back tomorrow to troubleshoot.

valid niche
#

just downsides

night crater
#

well what is it saying?

night crater
#

okay well I would recommend not having a bare except

#

but for the purpose of debugging and time

#

add this import statement

#

from traceback import print_exc

#

and in the except block as the first line add

print_exc()```
#

and see what it prints in the terminal

#

okay so the api is rejecting you because your embed is invalid

#

which means the api is returning None for location (or maybe country_name I cant remember if discord accounts for indexing at 0)

valid niche
#

your 7th field has a value that is missing

night crater
#

well the value is being passed, it's just None or empty

#

that discord doesnt accept

#

probably the best fix is using the or statement to see if it's a falsey value (None, False, Empty string etc...) and swapping it with some default e.g. "None"

#

!e ```py

foo = None
print(foo or "Hello")

foo = "Hello, World"
print(foo or "Hello")

unkempt canyonBOT
#

@night crater :white_check_mark: Your eval job has completed with return code 0.

001 | Hello
002 | Hello, World
visual island
#

pass something to the embed field's value

slate swan
#

im trying to do a download bar for my discord bot when it logs in theirs a download bar but nothin shows up

def start():
     tasks = 10
     x = 0
     while(x<tasks):
        time.sleep(1)
        bar["value"]+=10
        x+=1
        percent.set(str(int((x/tasks)*100))+"%")
        text.set(str(x)+"/"+str(tasks)+"tasks completed")
        window.update_idletasks()
        window.mainloop()
        window = Tk()
        percent = StringVar()
        bar = Progressbar(window,orient=HORIZONTAL,length=300)
        bar.pack(pady=10)
        percentLabel = Label(window,textvariable=percent).pack()
        text = StringVar()
        button = Button(window,text="download",command=start).pack()
valid niche
#

i have my doubts one can use TkInter with a discord bot

#

seeing as it's completely blocking and such

slate swan
valid niche
#

wut?

slate swan
# valid niche wut?

should i do

def on_ready():
     tasks = 10
     x = 0
     while(x<tasks):
        time.sleep(1)
        bar["value"]+=10
        x+=1
        percent.set(str(int((x/tasks)*100))+"%")
        text.set(str(x)+"/"+str(tasks)+"tasks completed")
        window.update_idletasks()
        window.mainloop()
        window = Tk()
        percent = StringVar()
        bar = Progressbar(window,orient=HORIZONTAL,length=300)
        bar.pack(pady=10)
        percentLabel = Label(window,textvariable=percent).pack()
        text = StringVar()
        button = Button(window,text="download",command=start).pack()
valid niche
#

sorry but what

slate swan
night crater
#

pithink I dont think thats a Discord thing

valid niche
#

i just told you that TkInter probably isn't compatible with discord.py at all

valid niche
#

using TkInter

#

but i don't think that works like that

night crater
#

pithink There isn't really any 'progress' other than shards starting

slate swan
valid niche
#

that too

night crater
#

If you really really want a UI like that then use Kivy with it's asyncio backend

valid niche
#

it's just connect, heartbeat, identify and done

#

for each shard

night crater
#

but in reality it would be better to have a API where they relay it to a web server that then renders it as HTML for you

valid niche
#

that would be something that would actually be possible yes, a separate application that communicates

night crater
#

depends what you want to do with them

#

If your bot doesnt absolutely need the gateway / websocket events then you can use a HTTP server approach

#

But there is quite a bit of boiler plate code and not many libs around really

#

I do maintain my own framework for slash commands designed entirely around the HTTP server side of stuff for minimal boiler plate though: https://github.com/ChillFish8/roid

honest wing
#
OSError: Multiple exceptions: [Errno 111] Connect call failed ('::1', 5432, 0, 0), [Errno 111] Connect call failed ('127.0.0.1', 5432)

Getting this error from switching to Windows to Arch Linux, can't find a proper answer anywhere. Using asyncpg with postgres.

async def create_db_pool():
    bot.db = await asyncpg.create_pool(database = "prefix", user = "user", password = "pwd")
    print("Connected to database.")```

Thanks!
night crater
#

Apparently asyncpg cant connect to the postgres server

#

are you sure it's running / exposed correctly? (the db)

honest wing
#

Yes it's running

valid niche
#

also postgres servers need to be set to allow outside connections if you're connection from another computer

valid niche
#

at the bottom there are the connection settings

#

for instance

# IPv4 local connections:
host    all         all         127.0.0.1/32          md5
host    all         all         10.1.2.28/32          md5
#

the top one being localhost and the bottom one being a random computer

#
  • for all IPs if you want anyone to connect from anywhere
honest wing
#

Alright thank you

dapper cobalt
#

Can you show your code?

#

!paste if it's too big.

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

reef shell
#

Imagine

lost lagoon
#

how would i implement a mute command

lyric moat
#

how do i make anti invite?

sleek ore
#

It would probably because the request errors

#

Try it with a valid number code

#

Then try it with a wrong one

#

Oh yeah, usually APIs have somekind of a success key, like "success": True or "code": 400

#

Try adding it to the code

if success:
    # do all the embed stuffs
else:
    await ctx.send("There's something wrong")
heavy radish
#

.

#

I managed to do it. But it doesn't work other than vsc

slate swan
#

Is anyone interested in helping me develop a discord bot for a strategy game that runs in the server? It's similar to those IDLE RPG bots.

inland venture
#

if user_message.startswith('your'):
response = f'you're*'
await message.channel.send(response)
return

#

i got error

little ether
dapper cobalt
slate swan
#

i keep getting a eol while scanning string literal in "eve" on event:

otherlist = ("-----bot-----", "-----version 1.0-----","0%|          |","25%|███       |","50%|████    |","75%|███████   |","
100%|██████████|")

@bot.event
dapper cobalt
inland venture
dapper cobalt
inland venture
#

ayayaya ty

dapper cobalt
#

It's because your string is ' ' and you used ' in "you're".

inland venture
#

thank u so much

dapper cobalt
#

Np

sleek ore
slate swan
sleek ore
#

note, you can do this aswell 'you\'re'

dapper cobalt
slate swan
dapper cobalt
slate swan
# dapper cobalt Show me your new code.

the code related to the problem:

otherlist = ("-----Nicebot-----", "-----version 10.0-----","0%|          |","25%|███       |","50%|████    |","75%|███████   |","
100%|██████████|")

@bot.event
async def on_ready():
     print("we have logged in as Nicebot and its ready to use.")

for x in otherlist:
    print(x)  
dapper cobalt
slate swan
dapper cobalt
#

Can you show the full traceback?

slate swan
dapper cobalt
slate swan
#

thats what it says

dapper cobalt
#

!e

otherlist = ["-----Nicebot-----", "-----version 10.0-----","0%|          |", "25%|███       |" , "50%|████    |" , "75%|███████   |" ,"100%|██████████|"]

for x in otherlist:
  print(x)
unkempt canyonBOT
#

@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.

001 | -----Nicebot-----
002 | -----version 10.0-----
003 | 0%|          |
004 | 25%|███       |
005 | 50%|████    |
006 | 75%|███████   |
007 | 100%|██████████|
slate swan
dapper cobalt
#

You had an un-closed string. Probably you added the sentence in another line.

dapper cobalt
dapper cobalt
#

I'm not sure. I just re-wrote them all.

heavy radish
#

Hello

dapper cobalt
#

You may copy it if you want.

heavy radish
#

Why does @bot.group() not work on replit

dapper cobalt
#

Isn't it @commands.group()?

heavy radish
#

IDK

#

i'll try that

dapper cobalt
#

!d discord.ext.commands.group

unkempt canyonBOT
#

@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.

Changed in version 1.1: The `cls` parameter can now be passed.
dapper cobalt
#

!d discord.ext.commands.Bot.group

unkempt canyonBOT
#

@group(*args, **kwargs)```
A shortcut decorator that invokes [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
slate swan
dapper cobalt
#

I guess it's @commands.group().

#

Not sure about bot.group().

dapper cobalt
heavy radish
#

how about the other one

#

to start the commands

#

help.command()

dapper cobalt
#

Did you first remove your default help command?

heavy radish
burnt wharf
#

!d discord.Message.add_reaction

unkempt canyonBOT
#

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

Add a reaction to the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
heavy radish
#

help_command=None

patent lark
#

discord.ext.commands.Bot has a help_command kwarg in which you can set to none

#

yup ^

dapper cobalt
heavy radish
#

I copied this from My VSC

#

And yes, it worked

slate swan
dapper cobalt
#

But the help ping does not?

dapper cobalt
heavy radish
#

ye

#

no

dapper cobalt
#

Show me the code for the help ping.

heavy radish
#

It gives error

patent lark
heavy radish
#

Yes

dapper cobalt
#

Oh yes, I forgot about that.

heavy radish
#

Ik, but this is a help command

#

its in a group.command

dapper cobalt
#

You've got another function called ping.

heavy radish
#

yes

#

But this way worked on VSC

dapper cobalt
#

You can't have two functions with the same name. I think.

patent lark
#

i recommend moving it over to a different file.

heavy radish
#

How?

dapper cobalt
#

!e

async def foo():
  pass

async def foo():
  pass
unkempt canyonBOT
#

@dapper cobalt :warning: Your eval job has completed with return code 0.

[No output]
dapper cobalt
heavy radish
#

UMM

#

Can you help me with it??

patent lark
#

do you know OOP?

heavy radish
#

No

#

I just use everything in one file...

patent lark
dapper cobalt
#

That's a bad way to make a Discord bot.

heavy radish
#

Hm

#

Can you help me with COGS

dapper cobalt
#

I think I can spoonfeed you a little bit.

heavy radish
#

I saw a video

#

Oh Yay

dapper cobalt
#

But for $100.

heavy radish
#

It looked confusing

dapper cobalt
#

Just kidding.

heavy radish
#

I wish

#

I don't even have 100$

#

So do you want me to make a channel or DMs?

slate swan
dapper cobalt
#

I'll make a github public repository to be a template for using cogs. Give me a moment.

heavy radish
#

Whaaaaaaaaat?

#

Just ping/DM once you're done

dapper cobalt
#

Sure.

burnt wharf
#

Is there a reason as to why it might say that the emoji is unknown:

message = await channel.send('Hello world')
await message.add_reaction(':wave:')```
#

The message itself sends though

dapper cobalt
#

Didn't take me much.

heavy radish
#

@dapper cobalt

burnt wharf
heavy radish
#

Heyy, is this supposed to be connected??

dapper cobalt
heavy radish
#

The line from class

#

is it supposed to be together? and keep ping on please

#

What happen here??

heavy radish
dapper cobalt
#

Also what is supposed to be together?

heavy radish
#

What is the error?

#
@bot.event
async def on_ready():
  for cog in os.listdir(r"cogs"): # Loop through each file in your "cogs" directory.
      if cog.endswith(".py"):
          try:
              cog = f"cogs.{cog.replace('.py', '')}"
              bot.load_extension(cog) # Load the file as an extension.
          except Exception as e:
              print(f"{cog} is failed to load:")
              raise e
    print(f"Logged in as {bot.user}")
``` Indention Problem??
dapper cobalt
#

2 on_ready events?

heavy radish
#

I'll remove the other

dapper cobalt
#

Just copy the code and paste it.

heavy radish
#

Massive Load

boreal ravine
heavy radish
#

More like copy pasting through

boreal ravine
#

Bruh

heavy radish
#

I did run. It's be just loading for ages

#

F

burnt wharf
#

How do I get access to a message in which a reaction was posted on?

little ether
unkempt canyonBOT
boreal ravine
#

@slate swan Theres an in built help command you'll need to remove that one first

burnt wharf
boreal ravine
#

!d discord.ext.commands.Bot.remove_command

unkempt canyonBOT
#

remove_command(name)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to remove aliases.
boreal ravine
#

Its a string btw

dapper cobalt
#

bot.remove_command("help").

#

Can you show your code?

slate swan
#

could you show the part of the code where you are trying to do this?

#

You do that in the python script itself

#

Not in the terminal

#
bot = commands.Bot (.....)

bot.remove_command('help')```
dapper cobalt
boreal ravine
#

why did u copy that whole thing

#

did u put a name

hardy geyser
#

Quick question, is there a way my bot could get the ID of a user through an @ ping? Thanks

boreal ravine
#

it needs an argument

dapper cobalt
boreal ravine
#

.command("help)

hardy geyser
dapper cobalt
#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

hardy geyser
dapper cobalt
#

Returns a list of discord.Member object for mentioned users.

heavy radish
#
discord.errors.ClientException: Callback for help command is missing "ctx" parameter.
``` Help command is in COGS
dapper cobalt
#

No problem.

heavy radish
#

which one

dapper cobalt
#

You forgot to pass self.

boreal ravine
#

the command

heavy radish
#

no

slate swan
#

Happy to help

dapper cobalt
heavy radish
#

(ctx, self)

dapper cobalt
#

Wrong.

#

self before ctx.

heavy radish
#

(self, ctx)

#

??

slate swan
# heavy radish no

commands in cog :

@commands.command()
async def command(self , ctx ):
   .....```
heavy radish
#

Thank You

#

WTH

boreal ravine
heavy radish
#

You have help commands on

#

hm

#

thats weird

boreal ravine
#

Sir, its the default one. I've told u earlier

slate swan
#

Did you remove the help command?
If yes , just rerun the bot

heavy radish
#

help_command=None ??

boreal ravine
slate swan
#

they did the remove_command method

slate swan
boreal ravine
#

restart the bot

boreal ravine
slate swan
#

Ow

boreal ravine
#

Show the help command I guess?

slate swan
#

In your commands.Bot add , help_command= None

dapper cobalt
#

@heavy radish You clearly ignored comments.

heavy radish
#

Hmmm, Yea I fixed it. Thanks

#

BTW, Can I name the cogs folder as COGs or COGS

#

Lowercase looks weird

dapper cobalt
heavy radish
#

Oki

dapper cobalt
#
client.remove_command("help")
#

client.help_command = None?

slate swan
#

@slate swan does it send both of your help command and the one you don't want to?

#

you have your bot running multiple times , close all the previous tasks and run it again

#

If it's vsc , you can do it thru the run option in the sidebar

#

ah

#

no problems

boreal ravine
slate swan
#

wsp yo

fleet oracle
#

How can you make a bot with two languages? Example, English and Spanish

slate swan
#

how do i make my list like this?

commandslist = ("bot commands(always start with the (#) prefix ):
                command 1
                command 2
                command 3
                command 4")

so when you send it it looks like that from up to down in the middle

#

Is it possible to host a bot in pythonanywhere for free?

supple thorn
visual island
#

what's i18n?

slate swan
fleet oracle
supple thorn
#

I dont know why you had to ask it here

fleet oracle
supple thorn
#

But you can just add them

fleet oracle
supple thorn
#

It will work you dont have to ask it here

slate swan
#

Ive checked the pinned post here and they say that those services are not good for that. For repl.it as an example you need to run a server for the bot to not die, repl.it kills the process in an hour if the bot is not used iirc, and also need another service to ping the server. I think you can have a free page in pythonanywhere. That's why i was wondering if someone can use that

fleet oracle
supple thorn
#

You could literally add gibberish and english and it would work

supple thorn
#

If you want it to be by guild id or by user id

fleet oracle
slate swan
#

how does discordpy logging work in cogs?

#

discord-components

#

go to that server and ask them

boreal ravine
boreal ravine
#

Again. Replit ISN'T hosting site

#

Is it free though? Thats the question

slate swan
#

Yes

boreal ravine
#

it has free hosting but only for 28 days

#

:/

#

You said you were on replit though?

#

WTH I am hosting my bot for more than a month and I never got a warning

#

where is your bot right now? On heroku or replit??

woeful fable
#

google has 300 dollars plus 3 months free hosting

slate swan
#

Is blocked for my country

#

And i can't use vpn

#

Is the other way around

#

Heroku banned my country. So i was asking if someone here have tried using pythonanywhere

boreal ravine
#

whats pythonanywhere

brazen raft
#

PythonAnywhere only allows you to use http/s ports

slate swan
brazen raft
#

So no websockets

slate swan
#

Oh. Im a discord bot newbie, i thought they used http/s

#

Thanks for the help still

brazen raft
#

They do probably, alongside the websocket for your bot

slate swan
#

Lonely refusing to read discord components docs grumpchib

#

The discord bots don't use http?

#

How do you send a message to a specific channel

sick birch
slate swan
#

Client.get_channel

#

?

sick birch
#

or guild.get_channel

#

2nd one is more efficient but both work

slate swan
#

So would the id be an int or str

sick birch
#

int

slate swan
#

So client.get_channel(1234567890)

#

correct @slate swan

drifting arrow
#

Looks correct @slate swan

#

also someone tagged me here earlier

heavy radish
drifting arrow
heavy radish
drifting arrow
#

Or do we move on?

drifting arrow
#

pretty sure it's something like ctx.author and author is the member object

drifting arrow
#

@umbral fossil it'd be something like ctx.author.roles

slate swan
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

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

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

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

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

I'm confused. did you want to check before the command ran? or during?

slate swan
drifting arrow
#

That's also a thing sure.

#

Many different ways to get the same result \o/

slate swan
#

ye

drifting arrow
#

One of the great things about programming

slate swan
#

wsp wsp

drifting arrow
slate swan
#

my tag is so good

#

no nitro 😹

vast gale
#

argh

#

I need to rewrite my paginator to be able to paginate embeds

drifting arrow
vast gale
#

yeah

#

it uses embeds tho

#

but it shouldn't be too hard to rewrite 😓

drifting arrow
#

Wouldn't you just do message.edit and basically put the same embed in except changing the variables?

vast gale
#

my paginator is a bit more complicated than that...

#

basically I need to add support for passing a list of embeds 😄