#discord-bots

1 messages · Page 489 of 1

slate swan
#

🤦‍♂️

sick birch
#

Does for me

hasty iron
#

its a method of the class

#

no it doesn't

stiff nexus
#
    @property
    def embed(self):
        page = self.pages.current_page

        
        e = discord.Embed(color=0xffffff)
        if self.title:
            e.title = self.title

        e.description = page.content

        
        if self.show_page_count:
            e.set_footer(text=f"Page {page.index} of {self.pages.total}",icon_url=self.ctx.author.display_avatar)

        return e
``` how do i add `author` `image` and `thumbnail` in this property????
sick birch
#

Dunno, worked for me after I changed the name

reef mica
#

_ doesnt work

#

I changed it to kick beacuse the ban didnt work, but they either dont work

sick birch
#

Then it’s something else

reef mica
#

no exceptions no nothing

sick birch
#

Maybe client.command

#

Are you using bot or client?

#

Client has no sense of a “command”

slate swan
#

are you joking

reef mica
#
client = commands.Bot(command_prefix='$')
sick birch
#

Hmm

#

Suggest you change the name for good practices

boreal ravine
#
@commands.command(name=f'help {command_name}')
  async def _hep(self, ctx, *, command_name:str):
    command = self.client.get_command(command_name)
    await ctx.send(command.name, command.aliases, command.help)
``` how do I make it so when the user does the command its like `.help ban`
sick birch
#

Make sure the bot has perms

reef mica
#

it has admin

sick birch
#

Are you trying to have the bot kick you?

#

Hierarchy

#

The bot has to be above the person it’s trying to kick

stark hearth
boreal ravine
slate swan
#

Hey where is the bot commands channel?

boreal ravine
#

hm

boreal ravine
sick birch
slate swan
#

thanks

boreal ravine
#

!d discord.ext.commands.Group

unkempt canyonBOT
#

class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
boreal ravine
#

hm

hasty iron
stiff nexus
#

k

boreal ravine
reef mica
boreal ravine
boreal ravine
reef mica
#

it should

boreal ravine
#

go check

hasty iron
drifting arrow
#

I believe message.content is a string. however you can convert it to an int

#

You also have to make sure it is an int as well. so strip everything but the numbers

spring flax
#

yes it returns a string

#

!d discord.Message.content

unkempt canyonBOT
spring flax
#

Type: str

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

reef mica
#

So I finally found the issue why the ban command didnt work

#

any command doesnt work

#

I have

from discord.ext import commands

client = commands.Bot(command_prefix="!")

@client.command()
async def hello(ctx):
    await ctx.send("Hello")

even this doesnt work

#

and i dont know why

reef shell
#

you are lacking intents

#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").

New in version 1.5...
reef mica
#

since when is this a thing

rustic lily
#

like, a year ago

#

or so, i think

#

october 7th

reef mica
#

im literally looking at a tutorial from 2021 january and it has no intents

rustic lily
#

bru h

stark hearth
#

I was in class my bad

#

@boreal ravine

slate swan
#

are there any bots that provide indentation like the python bot here does?

icy seal
# reef mica since when is this a thing

actually i was a little confused about this too - i have code from possibly an old version of discordpy that doesn’t use intents in any way, but still works fine (on my own server with only me on it)… Why doesn’t it need intents?

#

Av what do you mean by provide indentation..?

slate swan
#

like
%fixmycode

if hello:
print("hello")```
#

and it indents it

#

innit

#

yes

#

well that's kinda poop

icy seal
#

Oh, so something that is able to uh, parse python code?

slate swan
#

and also the colour coding

#

you should be able to do that

#

yourself

icy seal
#

the colour coding is native to discord

#

you don’t need a bot for that

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

wait what

#

oh

#

wait leme try that

icy seal
#

bot has nothing to do with that

slate swan
#
#hello
reef mica
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!")

@client.command()
async def hello(ctx):
    await ctx.send("Hello")

this still doesnt work

slate swan
#

oh yea i dont need the bot

#

thanks

reef mica
#

wdym

slate swan
#

client.run

#

don't tell me you forgot that

reef mica
#

it has that

#

i just cut it off

#

so you dont see the token

slate swan
#

nice

#

so do you have an error?

reef mica
#

No

#

i have nothing

#

i have it not working

icy seal
#

you haven’t indented client.run have you

slate swan
#

so if you write
!hello
it doesn't do anything

reef mica
#

yes

#

exactly

hasty iron
#

is that all your code

reef mica
#

yes

slate swan
#

put the client.run() part without the token

#

in the message

#

not in the code

#

I mean send it

reef mica
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!")

@client.command()
async def hello(ctx):
    await ctx.send("Hello")

client.run("token her")
urban snow
#

What error r u getting

slate swan
#

well that should just work

reef mica
#

well ur dealing with me and for me nothing ever works

slate swan
#

does he need an on_ready?

hasty iron
#

do you get an error

slate swan
#

is it necessary?

hasty iron
#

an on_ready isn’t needed but would help here

urban snow
#

Error ss please

reef mica
#

no error

urban snow
#

So you r saying that it doesn't respond

reef mica
#

let me put it into vscode

urban snow
#

On !hello

reef mica
#

maybe that helps

hasty iron
#

are you running the code

reef mica
#

it is running

slate swan
#

!d discord.TextChannel.last_message

unkempt canyonBOT
#

property last_message: Optional[Message]```
Fetches the last message from this channel in cache.

The message might not be valid or point to an existing message.

Reliable Fetching

For a slightly more reliable method of fetching the last message, consider using either [`history()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.history "discord.TextChannel.history") or [`fetch_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.fetch_message "discord.TextChannel.fetch_message") with the [`last_message_id`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.last_message_id "discord.TextChannel.last_message_id") attribute.
urban snow
#

Is ur bot online

reef mica
#

it is

hasty iron
# reef mica

are you sure you’re running the correct file

urban snow
#

Alright

hasty iron
#

did you save your file

reef mica
#

ok

urban snow
#

Type !hello and check the pycharm console

reef mica
#

i put it into vscode

#

and it works

#

wut dafuq

slate swan
#

pycharm on bottom

#

nah, I really don't know what the problem was

reef mica
#

FAK

slate swan
#

that would be rookie af

reef mica
#

now i started adding in the old code

#

and it broke again

#

SHIT

slate swan
#

msg = channel.last_message

reef mica
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", intents=intents)

@client.event
async def on_ready():
    print("Bot is running as {0.user}".format(client))

@client.event
async def on_message(message):
    date_of_creation = str(message.created_at)
    author = str(message.author)
    content = str(message.content)
    if not message.author.bot:
        log_line = date_of_creation + " | " + author + ": " + content
        print(log_line)
        await client.get_channel(890228413988732948).send(log_line)

@client.command()
async def hello(ctx):
    print("Hello")
    await ctx.send("Hello")

slate swan
#

error?

reef mica
#

no error

slate swan
#

oh wait yeah

#

yes

reef mica
#

i didnt see what u said

slate swan
#

don't mind that

#

where's the part that doesn't work

reef mica
#

the !hello part

#

the logs work

slate swan
#

how can I be so dumb

#

the on_message stopped it

reef mica
#

why

#

is that

slate swan
#

replace @client.event before the on_message

#

to @client.listen()

reef mica
#

can u explain

#

what it does

slate swan
#

still processes commands

reef mica
#

but why cant there be the client.event

hasty iron
#

client.event does a setattr on client overriding any existing event, by default it has an on_message event registered that process commands, when you do a client.event on an on_message function it overrides it

slate swan
#

dpy

#

but here you go cuz blanket has read the full source code of dpy

#

impressive af

hasty iron
#

not really

reef mica
#

do i need to change the on_ready aswell?

slate swan
#

no

reef mica
#

IT FUCKING WORKS

#

FINALLY

hasty iron
#

it only affects on_message

#

dont worry about anything else

reef mica
#

IT HAS BEEN 5 HOURS

slate swan
#

wat

wise swift
#

what's the problem

hasty iron
#

call it

#

but otherwise yes

reef mica
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", intents=intents)

@client.event
async def on_ready():
    print("Bot is running as {0.user}".format(client))

@client.listen()
async def on_message(message):
    date_of_creation = str(message.created_at)
    author = str(message.author)
    content = str(message.content)
    if not message.author.bot:
        log_line = date_of_creation + " | " + author + ": " + content
        print(log_line)
        await client.get_channel(890228413988732948).send(log_line)

@client.command()
async def ban(ctx, member : discord.Member, *, reason="For being a jerk"):
    print("Ban Initiated")
    await member.ban(reason=reason)

client.run("token  here")
#

wasnt expecting to be back so early

#

but this doesnt work

hasty iron
reef mica
#

the ban

#

more specifically

#

nothing appears in console either

hasty iron
#

what doesn’t work about it

reef mica
#
  1. It doesnt ban
  2. the "Ban Initiated" doesnt appear in console
hasty iron
#

how are you invoking the command

reef mica
#

$ban @reef mica

slate swan
#

!

#

😑 🤦‍♂️

hasty iron
#

your prefix is !

reef mica
#

i mean !

#

yes

#

its a faceplam indeed

#

bye bye

#

hoping not to be back here

sweet merlin
#

how do i count a reaction ?

slate swan
#

delete the last message and use the attribute from before

#

lol

#

or do the harder way

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
slate swan
#

good luck with that tho

#
await channel.last_message.delete()
msg = channel.last_message```
river walrus
#

Specially for something like a ticket system

lament mesa
#

check and see if the channels last message exist in the cache or use TextChannel.history

#

!d discord.Client.cached_messages

unkempt canyonBOT
#

property cached_messages: Sequence[Message]```
Read-only list of messages the connected client has cached.

New in version 1.1.
slate swan
#

pin this lmao

drifting arrow
slate swan
#

dpy server

#

treats everyone this way

lament mesa
slate swan
#

that's why I'm here and not there

#

scary

drifting arrow
#

From where?

#

oh

#

why did you get banned?

grim oar
#

For breathing

dapper cobalt
wise swift
#

how do I delete a limited amount of messages like $clear 5 and it'll clear 5 msg

slate swan
#

!d discord.TextChannel.purge

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...
wise swift
#

any example ?

boreal ravine
#

thats the example

#

await channel.purge(limit=5)

boreal ravine
slate swan
#

hey is it possible to make a music bot that streams music from spotify or is it against their tos too?

lament mesa
#

it is against their tos iirc

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

full lily
#

unless you use the built in discord spotify streaming feature ^^

slate swan
#

like i wanna do like .play (link)

slate swan
river walrus
#

You must have misread

upbeat otter
#

guys which event should i use to check if a member left the server?

valid perch
#

Using the code from dpy is basically like forking without license attribution tho thinkmon

#

Gah, sec

slate swan
unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

That one

upbeat otter
#

kk thenx

drifting arrow
#

Yeah is good

stark bobcat
#

why error

boreal ravine
#

@stark bobcat show setup func

gloomy coral
#

send code of setup

stark bobcat
lament mesa
#

you got invalid syntax

gloomy coral
#

and show full error

#

my bot still hasnt been verified

boreal ravine
#

not that

stark bobcat
#

sry

#

realised it mb

#
import discord
from discord.ext import commands
import json

class bot_join(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
    
    @commands.command()
    async def setup(self, ctx):
        all_channels = []
        all_categories = []
        for category in ctx.guild.categories:
            all_categories.append(category)
        for channel in ctx.guild.text_channels:
                all_channels.append(channel.id)
             
        category_exists = False
        channel_exists = False
        for i in all_channels:
            channel = self.bot.get_channel(i)
            if channel.name == 'mailer-logs':
                channel_exists = True
        for i in all_categories:
            if i.name == 'Mailer':
                category_exists = True

        if category_exists == True and channel_exists == True:
            embed = discord.Embed(description=f"Bot is already setted up",color=0xFF0000)
            await ctx.send(embed=embed)
        else:
            x = await ctx.guild.create_category('Mailer')
            y = await ctx.guild.create_text_channel('mailer-logs',category=x)

            embed = discord.Embed(title="Setup",description=f"Bot has been setted up!, use ``-accessrole[roles]``to give staff access to the channel.Check out more information and configurations with ``-help``.",color=0x1793FC)
            await ctx.send(embed=embed)
    

    @commands.command()
    async def access(self,ctx,arg): 
        open("DataBase/setup_data.json", "r") as file:
            data0 = json.load(file)
        data0[arg]=1
        open("DataBase/setup_data.json", "w") as f:
            json.dump(data0,f,indent=4)
        
        
def setup(bot):
    bot.add_cog(bot_join(bot)) ```
#

it's smth wrong with the access command

boreal ravine
#

hmm

drifting arrow
#

async def access(self,ctx,arg):? it's saying line 42 and this is line 42

#

wait no

stark bobcat
#

wym

drifting arrow
#

open("DataBase/setup_data.json", "r") as file: is line 42

lament mesa
#

you forgot the with

stark bobcat
drifting arrow
stark bobcat
#

ok lemma do that

stark bobcat
drifting arrow
#

You're fortunate it's so high up and you got a line number

#

I sometimes get errors somewhere around like 500 but the real error occurred 100 lines up

stark bobcat
#

@lament mesa

lament mesa
#

a function is calling itself and causing recursion

stark bobcat
#

what's recursion

stark bobcat
#

how do i fix it

lament mesa
unkempt canyonBOT
#

@lament mesa :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 |   File "<string>", line 2, in foo
004 |   File "<string>", line 2, in foo
005 |   File "<string>", line 2, in foo
006 |   [Previous line repeated 996 more times]
007 | RecursionError: maximum recursion depth exceeded
stark bobcat
#

ohhh

#

but

#

my code doesn't have something like that

rocky hamlet
#

Does anyone know what this error mean?
File "C:\Users\Nothhing\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke await ctx.command.invoke(ctx)

slate swan
#

that comes from the source code bruh

rocky hamlet
#

ik

slate swan
#

there's an error for you too

rocky hamlet
#

wdym

upbeat otter
#

guys, is this okay to define 2 hours 🥲

await asyncio.sleep((60*60)*2)
upbeat otter
#

maybe i am extraordianary

#

idk

river walrus
#

I'm asking for what you're doing

#

Maybe there's a better method

upbeat otter
river walrus
upbeat otter
slate swan
#

does anyone know ant working discord bot clients? i need to find a way to send a message in every server my bots in stating its going out of service and a new one will be coming

slate swan
#

hmmmmm fix ?

river walrus
slate swan
#

yes but how 😂

river walrus
hasty iron
#

you probably indented somewhere you shouldn’t have

#

or missed a :

slate swan
# river walrus Fix your indent
import discord
import json

bot = discord.Client()

with open("config.json", "r") as config:
    get = json.load(config)
    token = get["token"]
    title = get["embed_title"]
    description = get["embed_description"]
    thumbnail = get["embed_thumbnail"]
    image = get["embed_image"]
    footer = get["embed_footer_text"]
    icon = get["embed_footer_icon"]

embed = discord.Embed(title=title, description=description, color=0xffffff)
embed.set_thumbnail(url=thumbnail)
embed.set_image(url=image)
embed.set_footer(text=footer, icon_url=icon)

@bot.event
async def on_connect():
  print("User Logged Into:")
  print("-----------------")
  print(bot.user.name)
  print(bot.user.id)
  print("-----------------")
  print("Started dm..")
  print("-----------------")

  for user in bot.user.friends:
    try:
      await user.send(embed=embed)
      print(f"Successfully message sent to: {user.name}")
    except:
      print(f"Failed to send message to: {user.name}")
   print(f"{bot.user.name} hass finished dm !")

bot.run(token, bot=True)

hasty iron
#

a self bot

slate swan
#

?

hasty iron
#

!rule 5

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
#

No selfbot

hasty iron
#

it is a self bot

slate swan
#

no

#

bot

hasty iron
#

for what reason you have bot=False

slate swan
#

oops

#

I just want fix

#

the problem

#

intdent

hasty iron
#

we can’t help

slate swan
#

Bot = true

hasty iron
#

it breaks ToS, thus breaking rule 5

river walrus
slate swan
#

Bro

#

How to fix intdent

hasty iron
#

learn python

slate swan
#

Just my bot

hasty iron
#

and we can’t help with selfbots

slate swan
hasty iron
#

ok then fix it

slate swan
#

I need help no unemploy

drifting arrow
#

dafuq. why isnt this picking up json?

import requests
import json


class myreddit(object):

    def __init__(self):
        self.client_id = 'adsasdas'
        self.secret_key = 'asdad'
        self.username = 'adsad'
        self.password = 'asdad'
        self.headers = self.get_headers()
        
    def connect(self):
        auth = requests.auth.HTTPBasicAuth(self.client_id, self.secret_key)
        data = {
            'grant_type': 'password',
            'username': self.username,
            'password': self.password
            }
        response = requests.post('https://www.reddit.com/api/v1/access_token', auth=auth, data=data, headers=self.headers)
        TOKEN = response.json()['access_token']
        self.headers['Authorization'] = f'bearer {TOKEN}'
``` I know the code works since I used this code on a different project. 🤔
hasty iron
#

but it is

river walrus
#

<@&831776746206265384>

bitter halo
#

!mute 874671767933820929 investigating

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1632336176:f> (59 minutes and 59 seconds).

hasty iron
#

and if you plan on using that with a bot, use aiohttp

crimson pulsar
#

lets not use such language

leaden jasper
#

How to skip to end of task?

hasty iron
#

wdym

leaden jasper
#

and start waiting

bitter halo
# hasty iron learn python

This is not an appropriate response to someone here. We prefer you send someone to resources if they need beginner-level help. Feel free to ping moderators if you believe someone is breaking the rules.

slate swan
spring flax
#

Hey Fisher

drifting arrow
hasty iron
slate swan
#

@spring flax do u know how to send a message to every server a bots in?

#

i understand ratelimits but its only 18 servers

spring flax
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
leaden jasper
spring flax
#

@slate swan ^

drifting arrow
hasty iron
#

i meant the json stdlib

#

you dont need it

drifting arrow
#

dont need to import it?

hasty iron
hasty iron
drifting arrow
#

neato then

leaden jasper
slate swan
# spring flax <@456226577798135808> ^
bot = discord.Client()
await bot.wait_until_ready()
channels = []
for server in bot.servers:
  for channel in server.channels:
     channels.append(channel)
     await ctx.send(message=f"hello")``` could this work?
hasty iron
leaden jasper
#

ok

hasty iron
#

ctx is not defined

#

and await doesnt work outside async functions

slate swan
#
@bot.command(pass_context=True)
async def broadcast(ctx, *, msg):
    for guild in bot.guilds:
        for channel in guild.channels:
            try:
                await ctx.send(message=f"a")
            except Exception:
                continue
            else:
                break``` what about this
hasty iron
#

that’s old code

slate swan
#

that's really outdated

hasty iron
#

dont copy code off the internet

slate swan
#

server -> guild now

#

i just dont know what to work off of

#

pass context isn't needed

hasty iron
unkempt canyonBOT
#

property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
hasty iron
#

!d discord.Guild.text_channels

unkempt canyonBOT
#

property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.

This is sorted by the position and are in UI order from top to bottom.
slate swan
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

bot.send is outdated also

rich brook
#

Bruh I thought this was #python-general

hybrid fjord
#

how (or even if i can) do i use the wait_for to listen for attachments

spring flax
#

@slate swan all channels of all guilds a bot is in is a large amount

vernal sundial
#

Is there any explanation anywhere that explains why guild.members returns an empty list [] but guild.fetch_members().flatten() returns the list of members as expected?

I'm running into an issue where guild.fetch_roles() is returning a list of Roles but none of the roles are showing any members, but I can see that members have roles as expected when fetching the entire member list. I just want to easily get all the members of a certain role without having to iterate over all of the members and check if they have it.

slate swan
unkempt canyonBOT
hybrid fjord
#

cheers

slate swan
#

wait for a message and check if the message has attachments

vernal sundial
#

Yeah

slate swan
#
@bot.command()
async def broadcast(ctx):
    for guild in bot.guilds:
        embed = discord.Embed(title=f"Public Service Announcement",
                              description=f'service message',
                              color=0xf6dbd8)
        await channel.send(embed=embed)``` im trying to send a message to all servers my bot is in (18), could this source work?
hybrid fjord
#

@slate swan is there any possibility i can make it work like this or is it strictly wait_for only?

slate swan
#

!d discord.on_message

unkempt canyonBOT
#

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

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
slate swan
#
@bot.command()
async def broadcast(ctx):
    for guild in bot.guilds:
        embed = discord.Embed(title=f"Public Service Announcement",
                              description=f'service message',
                              color=0xf6dbd8)
        await channel.send(embed=embed)``` im trying to send a message to all servers my bot is in (18), could this source work?
#

how do i send a embed in discord.py this is my code:
@bot.command()
async def kick(ctx, member : discord.Member, *, reason="no reason given"):
await member.kick(reason=reason)
await ctx.send(f"{member} has been kicked for {reason}")

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

slate swan
primal mist
#
from discord.ext import commands
client=discord.Client()
client=commands.Bot(command_prefix="!")

@client.event
async def on_ready():
 await client.change_presence(status=discord.Status.online, activity=discord.Game('Watching you'))
  print("I am ready")



@client.command()
async def ping(ctx):
  await ctx.send("pong")





client.run("deleted token for puposes")```
#

It says error where highlighted

slate swan
primal mist
slate swan
#

resend that message in code format

primal mist
#

how?

slate swan
#

```message```

#

ill fix it

#

1 sec

primal mist
#

k

#

ty

slate swan
#

@primal mist

#
import discord 
from discord.ext import commands
client=discord.Client()
client=commands.Bot(command_prefix="!")

@client.event
async def on_ready():
    print("I am ready")
    await client.change_presence(status=discord.Status.online, activity=discord.Game('Watching you'))

@client.command()
async def ping(ctx):
    await ctx.send("pong")```
primal mist
#

ty

slate swan
#

that should work

#
@bot.command()
async def broadcast(ctx):
    for guild in bot.guilds:
        embed = discord.Embed(title=f"Public Service Announcement",
                              description=f'service message',
                              color=0xf6dbd8)
        await channel.send(embed=embed)``` im trying to send a message to all servers my bot is in (18), could this source work?
primal mist
#

Ty

slate swan
#

yw

#

how do i put a cooldown on a cooldown error

#

Hello Guys, Im new to discord.py and trying to learn and facing big errors i cant understand can someone help

#

send the error

#
 * Serving Flask app '' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.18.0.16:8080/ (Press CTRL+C to quit)
172.18.0.1 - - [22/Sep/2021 18:07:54] "GET / HTTP/1.1" 200 -
Traceback (most recent call last):
  File "main.py", line 405, in <module>
    client.run(os.getenv('TOKEN'))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discor
 * Serving Flask app '' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.18.0.16:8080/ (Press CTRL+C to quit)
172.18.0.1 - - [22/Sep/2021 18:11:25] "GET / HTTP/1.1" 200 -
Traceback (most recent call last):
  File "main.py", line 405, in <module>
    client.run(os.getenv('TOKEN'))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
 * Serving Flask app '' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.

#
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.18.0.16:8080/ (Press CTRL+C to quit)
172.18.0.1 - - [22/Sep/2021 18:11:50] "GET / HTTP/1.1" 200 -
Traceback (most recent call last):
  File "main.py", line 405, in <module>
    client.run(os.getenv('TOKEN'))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
 * Serving Flask app '' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.
 * Running on http://172.18.0.16:8080/ (Press CTRL+C to quit)
Traceback (most recent call last):
  File "main.py", line 405, in <module>
    client.run(os.getenv('TOKEN'))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)

#
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 216, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
 172.18.0.1 - - [22/Sep/2021 18:11:59] "GET / HTTP/1.1" 200 -
slate swan
slate swan
slate swan
slate swan
slate swan
#
@bot.command()
async def broadcast(ctx):
    for guild in bot.guilds():
        embed = discord.Embed(title=f"Public Service Announcement",
                              description=f'Hello Everyone, this announcement is by @simple matrix, the owner of Vaclav, Unfortunatly this bots service is coming to an end, however a new member of the community @drifting folio, Terror.#1337 will be taking over the source code, and will be fully managed and updated by him. For the updated invite link, simply DM the word \"Vaclav\" to him and he will send you the updated invite link for the new discord bot, Vaclav will be going offline permanently some time during the following 5 days, we thank you for using vaclav. \n-Steven',
                              color=0xf6dbd8)
        await ctx.send(embed=embed)
``` can this work?
#

im trying to send a message to every server my bot is in

slate swan
valid niche
#

look at your own code

slate swan
valid niche
#

where is it going according to your code?

valid niche
#

where is it sending it to?

slate swan
boreal ravine
slate swan
slate swan
boreal ravine
slate swan
boreal ravine
#

You can but idk how

slate swan
slate swan
#

so i cant code any discord bots for some time... okay thanks i guess...

slate swan
slate swan
#

does anyone know how to put a cooldown on a command cooldown so like when you get the message this command is on cooldown retry after it does something to make it not send that message again untill it is not on cooldown anymore?

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

dapper cobalt
pure totem
#

btw ya'll know any 24/7 hosters with no self command

#

like the one that says lazy loading and stuff like that idk the website tho

dapper cobalt
pure totem
#

like a discord bot hoster right

dapper cobalt
#

You can see their plans using a command in their bot.

slate swan
unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

I think I know how to fix it

lyric moat
#

why this gives an error?

def get_prefix(client,message):

    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)

    return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix)
client.remove_command("help")

@client.event
async def on_guild_join(guild):


    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = "$"

    with open("prefixes.json", "w") as f:
        json.dump(prefixes,f)


@client.command()
@commands.has_permissions(administrator = True)
async def changeprefix(ctx, prefix):

    with open("prefixes.json", "r") as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix

    with open("prefixes.json", "w") as f:
        json.dump(prefixes,f)    

    await ctx.send(f"The prefix was changed to {prefix}")```
rocky hamlet
#

nvm

slate swan
#

no wait i was right

slate swan
#

before u added the on_guild_join

slate swan
#

look for that guild id in your json file, pretty sure u won't find it

slate swan
lyric moat
#

alr

slate swan
#

or u could try to catch the KeyError

lyric moat
#

Thanks

slate swan
#
try:
  return prefixes[str(message.guild.id)]
except KeyError:
  return '!'  # As an example i put ``!`` as the default prefix, if you want smth else just put that
hasty iron
#

or you use dict.get

#

!d dict.get

unkempt canyonBOT
#

get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3.10/library/exceptions.html#KeyError "KeyError").
kindred epoch
slate swan
#

How to edit ctx.author to have perms to view a channel?

twin thicket
#
class Utility(commands.Cog):

    def __init__(self, client):
        self.client = client

    #Commands
    @commands.command()
    async def ping(self, ctx):
        """Pings the bot"""
        await ctx.send('Pong!')

    @commands.command()
    async def help(self, ctx):
        """Displays the help message"""
        cogs = client.get_cogs()
        print(cogs)
        embed = discord.Embed(
            description=''
        )


def setup(client):
    client.add_cog(Utility(client))
#

anyone know why this is returning client is not defined

#

in the second cmd

hasty iron
#

look carefully at what you have defined in your cog

#

client is not defined but there is something else that’s defined

twin thicket
#

self?

hasty iron
#

you can either use self.client or ctx.bot

twin thicket
#

got it

#

thanks

#

also how do I get all cogs

#

like all the names of all the categories

slate swan
#

hello using member: discord.Member how can i make something like if discord.Member.id == "851807466681008158":

#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
slate swan
#

thats not much help

delicate socket
fossil nexus
slate swan
twin thicket
#

anyone know why ```py
x = []
z = []
"""Displays the help message"""
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
name = filename.title()
cog = self.client.get_cog(name[:-3])
cmds = cog.get_commands()
for c in cmds:
z.append(c.name)
x.append(name[:-3])
print(x)

returns 
['Economy']
['Economy', 'Moderation']
['Economy', 'Moderation', 'Utility']
full lily
#

so that it is outside of the loop

twin thicket
#

ooooh

#

lmao thanks

#

how do I embed the default help command

flat solstice
#

https://srcb.in/EY8LUxRfMb THIS6L This is my error handler file. I have the first handler which works fine however it doesn't seem to catch event errors so I added the on_error listener which doesn't seem to be firing for some reason and I think it's getting swallowed by the first handler despite my if statement telling it not to, anyone know how I can get around this problem

reef shell
#

Hi guys

#

i need a code review

reef shell
twin thicket
reef shell
flat solstice
#

Is there a built in system for detecting when members get mentioned or would I have to do a on_message withmessage.content.contains(@) or something along those lines

stark hearth
slate swan
hasty iron
#

!d discord.on_error

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.9)").

If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.9)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
flat solstice
hasty iron
#

on_error only works with Bot.event

flat solstice
#

well that's annoying

flat solstice
hasty iron
#

and why aren’t you using the listener decorator for on_command_error

flat solstice
#

because I don't need to, it's working fine without it (i'm not 100% sure why tho)

hasty iron
#

that’s a weird way of doing things but ok

flat solstice
#

lol that's my coding style in a nutshell

flat solstice
#

Would this if statement check be valid? or will it throw any errors logic wise (ik that the self.bot.config is correct)py if member.guild.id == 287426617322504192 if self.bot.config.default_server is None else self.bot.config.default_server:

graceful gulch
bitter depot
flat solstice
final iron
#

Would would I use on_message_delete? If I print it in my console it sends a bunch of server/author information but it doesn't actually send the message

flat solstice
final iron
#

Yeah if I use message.content it prints the actual message

slate swan
#

the events in pycord cogs are @commands.Cog.listener?
my on_message events aren't working

lyric moat
quasi pawn
#

I made a command to only work in a specific channel but when a user uses it in another channel, the cd gets triggered. How do I prevent this from happening?

lyric moat
slate swan
hard ether
#

my school just blocked replit o7 anyone know another online ide I could use to code discord bots?

#

in python*

inland venture
#

if user_message.lower('*ping'):
await message.channel.send('Pong!' + {client.latency})
return

#

TypeError: str.lower() takes no arguments (1 given)

#

need help guys

little ether
inland venture
#

ty

#

wait I got await message.channel.send('Pong!'+ {client.latency}) TypeError: can only concatenate str (not "set") to str

little ether
inland venture
#

ty tyty

little ether
dapper cobalt
hard ether
dapper cobalt
#

Third iirc.

hard ether
#

tyty

hard ether
dusk pumice
#

i know where ctx is used but don,t know wgat ctx means.

#

What does ctx means?

hasty iron
dapper cobalt
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
dusk pumice
#

Oh if ctx=context than

#

await ctx.send()

#

is same with

#

await context.send()?

visual island
#

yea

visual island
slate swan
#

Code: ```py
@bot.event
async def on_guild_join(guild):
with open [prefixes("prefixes.json", "r")] as f:
prefixes = json.load(f)

prefixes[str(guild.id)] = "p!, P!"

with open("prefixes.json", "W") as f:
json.dump(prefixes, f, indent=4)

@bot.event
async def on_guild_remove(guild):
with open [prefixes("prefixes.json", "r")] as f:
prefixes = json.load(f)

prefixes.pop(str(guild.id))

with open("prefixes.json", "W") as f:
json.dump(prefixes, f, indent=4)

@bot.command(aliases=["prefix"])
@commands.has_guild_permissions(administrator=True)
async def setprefix(ctx, prefixset = None):

if (prefixset == None):
prefixset = "p!", "P!"

with open("prefixes.json", "r") as f:
prefixes = json.load(f)

prefixes[str(ctx.guild.id)] = prefixset

with open("prefixes.json", "w") as f:
json.dump(prefixes, f, indent=4)

await ctx.send(f":white_check_mark: The bot prefix has been successfully changed to {prefixset}.\n📚 Perms: Administrator")**Error:** py
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/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 979, in on_message
await self.process_commands(message)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 976, in process_commands
await self.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 943, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 424, in dispatch_error
await injected(ctx, error)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 77, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'set' object has no attribute 'MissingRequiredArgument'```

#

It was working than it got screwed, I might have deleted something but I am not sure.

visual island
#

can you show the upper exception?

slate swan
#
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 71, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 266, in eightball_error
    if isinstance(error, bot.commands.MissingRequiredArgument):
AttributeError: 'set' object has no attribute 'MissingRequiredArgument'```
#
@eightball.error
async def eightball_error(ctx, error):
  if isinstance(error, bot.commands.MissingRequiredArgument):
    await ctx.send(":x:Please include a question.")

@ban.error
async def ban_error(ctx, error):
  if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send(":x:Please include a specific member.")
  elif isinstance(error, bot.commands.MemberNotFound):
    await ctx.send(":x:Member was not found.")```
#
NameError: name 'AsyncWebhookAdapter' is not defined```

```py
            webhook = discord.Webhook.from_url(i.url, adapter=AsyncWebhookAdapter(session))
visual island
slate swan
#

well hold on that part is wrong I forgot to change it but I am pretty sure it still doesnt work

visual island
slate swan
#

one moment

slate swan
# slate swan **Code:** ```py @bot.event async def on_guild_join(guild): with open [prefixes...
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 979, in on_message
    await self.process_commands(message)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 976, in process_commands
    await self.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 943, in invoke
    await ctx.command.dispatch_error(ctx, exc)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 424, in dispatch_error
    await injected(ctx, error)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 77, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'set' object has no attribute 'MissingRequiredArgument'
Ignoring exception in command None:```
visual island
#

huh

#

show code

#

New code

slate swan
#

I replied to it

#

in the error

visual island
#

where does the error appear?

slate swan
#

hold on

#

Here: py prefixes = json.load(f)

visual island
#

how

#

show the upper error?

slate swan
#

Same from last: ```py
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 706, in _parse_arguments
kwargs[name] = 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: question is a required argument that is missing.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 71, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 266, in eightball_error
if isinstance(error, bot.commands.MissingRequiredArgument):
AttributeError: 'set' object has no attribute 'MissingRequiredArgument'```

visual island
#

you're still having the bot.

slate swan
#

damn where??

#

oh crap

#

nevermind

visual island
#

if isinstance(error, bot.)

slate swan
#

Im sorry I am brain dead rn

visual island
slate swan
#

Sick and Tired

#

lol

#

Thanks blushes

#

oh god

night scaffold
#

Working on a discord bot and I keep getting this error whenever I run the command, can somebody help me with this?

slate swan
#

kill me

night scaffold
slate swan
#

damnit

#

ok bye everyone

night scaffold
#

bye

visual island
night scaffold
#

oof alr

#

thanks though

visual island
#

actually @night scaffold, it's an ssl issue stated up here

night scaffold
#

I tried that and its still not working

visual island
night scaffold
#

Thank you!

slate swan
#
ctx.channel.create_webhook(name='lucid'),avatar="https://i.imgur.com/oBPXx0D.png" , reason=None)``` how do i get the avatar to work ?
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes

visual island
#

remove the bracket after name='lucid{}'

slate swan
#

oh thats not an error ignore it for now

#
@commands.Cog.listener()
    async def on_message(self, message):
        if not message.author.bot:
            with open('./databases/global_chat.json', 'r') as file:
                global_chat_data = json.load(file)
            channel_id = list(global_chat_data.values())
            if message.channel.id in channel_id:
                for ids in channel_id:
                    if message.channel.id != ids:
                        tchannel = self.client.get_channel(ids)
                        webhooks = await tchannel.webhooks()
                        webhook = utils.get(webhooks, name='Chat Global')
                        if webhook is None:
                            webhook = await tchannel.create_webhook(name='Chat Global')
                        await webhook.send(content=f'{message.content}', username=message.author.name, avatar_url=message.author.avatar.url)```
#

i think i get it

slate swan
night scaffold
slate swan
#

So it doesn't even show an error, it just doesn't happen

night scaffold
#

hm

slate swan
#

hm

#

            number = random.randint(10,99)
            str(number)
            x = await ctx.channel.create_webhook(name=f'lucid'+number,avatar="https://i.imgur.com/oBPXx0D.png" , reason=None)``` error ```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate str (not "int") to str```
upbeat vigil
#
@bot.event
async def on_message(message):
  if message.author.id == [817803095563173918]
    await message.channel.reply("ok")``` hey is there anything wrong with this code
slate phoenix
#

also it wont send the message because message.channel.reply wont work

#

either use .send or message.reply

hollow moat
#

or you could do number = str(random.randint(10, 99)

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

quaint shell
#

in discord.py is it possible to disable a client.event()? my bot can be pretty annoying at times and i was wondering if there was a a piece of syntax to disable it

hollow moat
#

okay

little ether
sweet merlin
#

help, how do i make command handler? i tried using but it still error type object 'commands' has no attribute 'errors'

@Hello.error
  async def Hello_error(self, ctx, error):
  if isinstance(error, commands.errors.MissingRequiredArgument):
    await ctx.send("Missing your args")```
jade jolt
river walrus
jade jolt
#

yes it is?

little ether
hollow moat
#

what was the issue

#

then

slate swan
sweet merlin
jade jolt
#

bruh what

hollow moat
#

i dont think that was the error but anw

slate swan
#

man just forget about it.

jade jolt
sweet merlin
#

s?

#

u mean MissingRequiredArguments or i run the command and add s?

jade jolt
#

first one

sweet merlin
jade jolt
#

?!

#

weird

sweet merlin
#

yeah

jade jolt
#

show me your imports

#

did you use commands as a variable name somewhere else?

sweet merlin
#

cogs:
import discord, os, time, random, asyncio
from datetime import datetime
from discord.ext import commands

main:
import os, time, discord
from discord.ext import commands
from webserver import keep_alive

jade jolt
#

thats replit?

sweet merlin
#

yeah

#

i use commands for the cogs file

jade jolt
#

hm. your code works on my machine.

sweet merlin
#

?!

#

lemme change my file name

jade jolt
#

what was it

sweet merlin
jade jolt
#

odd

sweet merlin
#

commands has no atribute missingblabla

lofty mulch
#

bruh

#

Restart your IDE?

#

Sometimes it's just the ide that's glitched out or smth

stoic galleon
#

!eval
@commands.command(aliases= ['bi'])
async def botinfo(self, ctx):
embed = discord.Embed(color=0x36393, timestamp=ctx.message.created_at)
embed.set_author(name= '**Jackal')
embed.add_field(name= 'Stats',value= f'Guilds {len(self.client.guilds)}\n__Users__ {len(self.client.users)}\n__Latency__ {round(self.client.latency * 1000)}',inline=True)
embed.add_field(name= 'Info',value= 'Python 3.8.2\n__DiscordPy__ 1.7.3\n__Version__ 1.0.1',inline=True)
await ctx.send(embed=embed)

unkempt canyonBOT
#

@stoic galleon :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     async def botinfo(self, ctx):
003 | IndentationError: unexpected indent
stoic galleon
#

discord indents r shit

jade jolt
#

no?

lofty mulch
#

does discord even indent

jade jolt
#

it doesnt.

#

the user has to lol

lofty mulch
#

lol

#

might be because you copied it straight out of a cog

#

gotta fix the blank indent space

sweet merlin
lofty mulch
#

then what happened

#

did you execute it

sweet merlin
#

still

#

yeah, i did execute it

lofty mulch
#

could you post the error

sweet merlin
#

sure

lofty mulch
#

and the exact line that's going wrong with it

stoic galleon
#

whats the issue it wont send and i dont get a error

lofty mulch
#

are you running the cog

#

or running the main file with the bot.run(token)

stoic galleon
#

every commad in tha cog works jus besides info

#

idk why

sweet merlin
#

ok now i got new error again

lofty mulch
#

doesn't work as?

#

not responding?

#

giving a error?

stark hearth
stoic galleon
#

not responding no errors no cog errors nun

stoic galleon
hollow moat
#

are you running the right command

lofty mulch
#

did you make sure to do ctrl + s

#

and did you restart the bot?

lofty mulch
sweet merlin
stark hearth
#

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

lofty mulch
#

yeah, IDE problems?

jade jolt
#

just reload, as it says to

stoic galleon
lofty mulch
#

send over the code for the command

sweet merlin
lofty mulch
stoic galleon
#
 
    @commands.command(aliases= ['bi'])
    async def botinfo(self, ctx):
        embed = discord.Embed(color=0x36393, timestamp=ctx.message.created_at)
        embed.set_author(name= '**Jackal**')
        embed.add_field(name= '**Stats**',value= f'__**Guilds**__ {len(self.client.guilds)}\n__**Users**__ {len(self.client.users)}\n__**Latency**__ {round(self.client.latency * 1000)}',inline=True)
        embed.add_field(name= '**Info**',value= '__**Python**__ 3.8.2\n__**DiscordPy**__ 1.7.3\n__**Version**__ 1.0.1',inline=True)
        await ctx.send(embed=embed)
sweet merlin
stark hearth
# sweet merlin

did you do if isinstance(error, commands.errors.MissingRequiredArgument):

lofty mulch
#

I didn't use it for my handler, atleast

lofty mulch
#

Sounds like it isn't recognizing the command for some reason

stark hearth
lofty mulch
#

Is everything okay with your class?

lofty mulch
#

C

sweet merlin
#

i think the problem is on commands

lofty mulch
dapper cobalt
#

!d discord.ext.commands.MissingRequiredArgument

unkempt canyonBOT
#

exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
lofty mulch
#

could you show it?

sweet merlin
stark hearth
dapper cobalt
#

Do you have "commands" defined elsewhere?

lofty mulch
#

that might be it

sweet merlin
dapper cobalt
#

Try changing it.

sweet merlin
#

ok i will change the file name and, try to delete the await bot.process_commands(message)

sweet merlin
stark hearth
#
    @commands.command()
    async def meme(self, ctx):
        
        subreddit = await reddit.subreddit("dankmemes")
        all_subs = []

        async for submission in subreddit.top(limit = 100):
            all_subs.append(submission)  

        random_sub = random.choice(all_subs)

        name = random_sub.title

        embed = discord.Embed(title = name)

        embed.set_image(url = random_sub.url)
        await ctx.send(embed = embed)

i am not sure what to change when you are doing multiple subreddits in asycpraw

sweet merlin
#

but the listener are works

jade jolt
sweet merlin
#

oh

tiny ibex
#
async def bruh(ctx):```
sweet merlin
#

@alex

tiny ibex
sweet merlin
#

the A

tiny ibex
sweet merlin
#

oh

tiny ibex
#

I used capital

#

Someone please helppp

tiny ibex
#

Doesn't work yet

#

Someone please help

#
```It can't find any command
#
async def jk(ctx):
  print("Bruh")```
dapper cobalt
#

Capital A.

#

@Alex.command()

tiny ibex
dapper cobalt
#

What's your instance now?

tiny ibex
dapper cobalt
#

Have you restarted?

tiny ibex
#

Ok ig the problem is something else

#
Suga.remove_command('help')
alex = commands.Bot(command_prefix = prefix)
alex.remove_command('help')
buttons = ButtonsClient(alex)```
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

tiny ibex
#

Wait it still doesn't work

#
import discord
from disnake.ext import commands as Suga_command
from discord.ext import commands
import requests
import io
import random
import aiohttp
import bs4
from discord_buttons_plugin import *
from keep_alive import keep_alive
from bs4 import BeautifulSoup as bs4

prefix = "luv "
Suga = Suga_command.Bot(command_prefix = prefix)
Suga.remove_command('help')
alex = commands.Bot(command_prefix = prefix)
alex.remove_command('help')
buttons = ButtonsClient(alex)```
#

Can someone help me

#

@dapper cobalt

dapper cobalt
#

Why do you have two bots?

#

Which ine are you running first?

tiny ibex
river walrus
#

Want the link?

tiny ibex
valid perch
#

Sure, I'll take a look

tiny ibex
#

I don't want to run both of them seperately

dapper cobalt
tiny ibex
#

I don't want to seperate them

dapper cobalt
#

You literally can't. I assume you are running Suga before alex, try replacing alex.command with Suga.command.

valid perch
#

define 'not working'

tiny ibex
#

@dapper cobalt I am sorry

#

I actually forgot to enter the token 😅

#

Now it's perfect 😃

#

Thanks for your help @dapper cobalt

worldly goblet
#
@bot.command()
async def webhook(ctx):
    a_list = []
    for i in range(2):
        f = await ctx.channel.create_webhook(name='name')
        a_list.append(f)
    for i in lst:
        print(i)
        await i.send('hello')```
dapper cobalt
#

No problem.

worldly goblet
#

whats wrong with the code ?

valid perch
#

lst isnt defined, printi) isnt python

worldly goblet
#

its still not working after fixing that

#

i cant edit the message for some weird reason

tiny ibex
#

for i in lst:

worldly goblet
#
@bot.command()
async def webhook(ctx):
    a_list = []
    for i in range(2):
        f = await ctx.channel.create_webhook(name='name')
        a_list.append(f)
    for i in a_lst:
        print(i)
        await i.send('hello')```
#

it still doesnt work 😕

jade jolt
#

why are you doing it in a list? unless i missed something

worldly goblet
#

no error sadly

river walrus
worldly goblet
#

it just doesnt work, it worked two times then stopped something like that

hollow moat
#

i have this meme command

 @commands.command()
    async def meme(self, ctx):
        subreddits = ['dankmemes', 'memes', 'meme', 'wholesomememes', 'comedyheaven',
                      'KidsAreFuckingStupid', 'cursedcomments', 'HolUp', 'blursedimages', 'rareinsults']
        subreddit = random.choice(subreddits)
        async with aiohttp.ClientSession() as cs:
            async with cs.get(f'https://www.reddit.com/r/{subreddit}/new.json?sort=hot') as r:
                res = await r.json(content_type=None)
                post = res['data']['children'][random.randint(0, 25)]
                url = post['data']['url']
                title = post['data']['title']
                embed = discord.Embed(title=title, description=f"haha")
                embed.set_image(url=url)
                embed.set_footer(text=f'meme from r/{subreddit}')
                await ctx.send(embed=embed)

and everything seems to work, but i get a JSONDecodeError("Expecting value", s, err.value) from None at the await r.json line. does anyone know why this happens?

trim barn
#

How do I add reactions to an embed

patent lark
#

no?

trim barn
#

How do I make it react to its own message?

dapper cobalt
#

!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.
patent lark
trim barn
#

i can use unicode?

patent lark
#

yes

trim barn
#

cool

#
await confirm_embed.client.add_reaction(["✅", "❌"])
#

would this work?

patent lark
#

well let me see the code.

trim barn
#
                    embed = discord.Embed(
                        title="BEFORE PROCEEDING FURTHER, PLEASE CONFIRM YOUR BALLOT.",
                        description=f"Please confirm you have cast your ballot for **{str(candidates[str(voted_for.content.upper())])}**. "
                                    f"React with :white_check_mark: to confirm, react with :x: to not.",
                        color=discord.Colour.orange()
                    )
                    embed.set_thumbnail(url=self.client.user.avatar_url_as(static_format="png"))
                    embed.set_footer(text="EasyBallot brought to you by ZeldinSystems")
                    confirm_embed = await ctx.send(embed=embed)

                    await confirm_embed.client.add_reaction(["✅", "❌"])
patent lark
#

why client ?

trim barn
#

idk

#

lucas vid ig

patent lark
#

remove client

trim barn
#

oh that

#

that was from the bad advice I was given earlier

patent lark
#

its also better to use bot as your commands.Bot variable, since discord.Client() is a thing, it can be considered better practice

trim barn
#

meh

#

maybe later

#

already too deep in

patent lark
trim barn
#

and now time to make wait_for reaction detection

#

yay

pliant gulch
#

flexing O(1) getitem and O(1) popitem message cache

dapper cobalt
pliant gulch
#

compared to discord.py dequeue with O(n) getitem and O(1) popitem

pliant gulch
dapper cobalt
#

My eyes need that.

pliant gulch
#

check out my github, it has my dotfiles

#

there inside of .config you will find the neovim config

dapper cobalt
#

Of course.

marsh dove
#

Is there anyone here who codes discord bots in python?
if so let me know, cus i need a hand creating one.

tiny ibex
#
async def clearl(ctx, *, amount):
    await buttons.send(
      content = "Are you sure you want to clear all the mesages?",
      channel = ctx.channel.id,
      components = [
        ActionRow([
          Button(
            label = "Yes!!",
            style = ButtonType().Primary,
            custom_id = "button_bruh"
          )
        ])
      ]
    )

@buttons.click
async def button_bruh(ctx):
  await ctx.reply("OH ok sure! Here you go!!")
  await ctx.channel.purge(limit=amount+1)
  main = "Your requested messages were deleted!!"
  embedVar = disnake.Embed(title=titld, description=main, color=0xa89c2c)
  await ctx.send(embed=embedVar, delete_after=10)```
#

Why is not working?

boreal ravine
#

error?

tiny ibex
boreal ravine
#

is the title kwarg defined? I see titld

tiny ibex
#

The bot just deleted last 2 msgs and that's it

tiny ibex
boreal ravine
#

meaning?

tiny ibex
# boreal ravine meaning?
async def button_bruh(ctx):
  await ctx.reply("OH ok sure! Here you go!!")
  await ctx.channel.purge(limit=amount+1)
  titld = "Deleted!!"
  main = "Your requested messages were deleted!!"
  embedVar = disnake.Embed(title=titld, description=main, color=0xa89c2c)
  await ctx.send(embed=embedVar, delete_after=10)

#

Added

boreal ravine
#

why is

#

the click above the button

tiny ibex
tiny ibex
#

@boreal ravine You here?

boreal ravine
#

yes

tiny ibex
patent lark
#

you set the limit parameter equal to amount. what is amount? where is this referenced in the code?

tiny ibex
marsh dove
#

@patent lark you desc says you will make bots 4 people. can u help me make mine 😏

patent lark
#

ah i didnt see that part of the code

boreal ravine
#

wait

boreal ravine
#

thats another command tho

patent lark
#

right

tiny ibex
patent lark
dapper cobalt
#

!code @tiny ibex do that instead.

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.

tiny ibex
# patent lark how do you expect these parameters to work outside the function call? in a diffe...
async def clearl(ctx, *, amount = 5):
    await buttons.send(
      content = "Are you sure you want to clear all the mesages?",
      channel = ctx.channel.id,
      components = [
        ActionRow([
          Button(
            label = "Yes!!",
            style = ButtonType().Primary,
            custom_id = "button_bruh"
          )
        ])
      ]
    )

@buttons.click
async def button_bruh(ctx):
  await ctx.reply("OH ok sure! Here you go!!")
  await ctx.channel.purge(limit=amount+1)
  titld = "Deleted!!"
  main = "Your requested messages were deleted!!"
  embedVar = disnake.Embed(title=titld, description=main, color=0xa89c2c)
  await ctx.send(embed=embedVar, delete_after=10)```
dapper cobalt
#

So we can read your code bet-

#

I'm too late, I guess.

tiny ibex
#

Isn't buttons.click subpart of suga.command?

ruby oracle
#

I've wanted to make one of these bots for a while. Any idea where to get started?

patent lark
ruby oracle
#

Discord bots in general lol

tiny ibex
marsh dove
#

can someone collab with me making a bot?

dapper cobalt
ruby oracle
#

I know a bit of Python

#

I'm currently taking some classes to learn more too

marsh dove
#

i am a profesional python coder i can do 50% of the work

patent lark
dapper cobalt
patent lark
#

i recommend you learn Python basics before touching up on discord.py

ruby oracle
dapper cobalt
#

async

ruby oracle
#

not yet

dapper cobalt
#
async def foo():
    pass
dapper cobalt
#

I suggest you learn basics of async.

tiny ibex
#

Understood

#

TY

ruby oracle
#

Like I said, I found a class that's gonna teach me everything about python so I'll come back after that

#

a few weeks ig

slate swan
#

everything about python :3

ruby oracle
#

Probably not EVERYTHING ig

patent lark
ruby oracle
#

There's always more

#

But teach me a lot

slate swan
ruby oracle
#

Yeah

#

I'm still pretty new at this

dapper cobalt
#

I want to get into whatever school teaches legitimate programming and not just very basics of HTML.

ruby oracle
#

I started getting into coding like last week lol

patent lark
#

ive taken many classes, but i am also pretty self-taught.

ruby oracle
#

So I know basic html that's about it 💀

dapper cobalt
patent lark
#

skelmis

valid perch
#

Idk, my education is legit programming but its a more conceptual then anything else

#

Like alogos n such vs 'just coding'

slate swan
#

if you put some efforts , python is a great beginner friendly langauge

valid perch
ruby oracle
#

Name of my class is "Python Programming, CS, Algorithms and Data Structures"

dapper cobalt
#

I don't want to be this guy, but..

#

!ot

unkempt canyonBOT
dapper cobalt
#

We've gone pretty off-topic.

slate swan
#

Yep

ruby oracle
#

True

patent lark
# valid perch Like alogos n such vs 'just coding'

yeah, i guess ive struggled with being taught within classes publicly, its kinda just half-ass effort into teaching, ive taken classes time and time again, id be lying if i said it didnt do me good, it did, but i am confident in saying i am majority self-taught

valid perch
#

Yea, besides. Self taught hands on coding is way better, anyway ye we off topic haha

patent lark
#

yeah haha

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

marsh dove
#

Hi, If anyone is interested in working on an economy bot with me let me know, i will lend you a hand on the coding process.

valid perch
#

So you'd help on our bot, or is it yours

pliant gulch
river walrus
#

I've actually thought of a method

marsh dove
pliant gulch
valid perch
river walrus
burnt ether
#

hewo, i need som halp,
how can i put dis in an embed?

pliant gulch
#

redis seems out of scope, how is the wrapper supposed to setup the redis server?

burnt ether
#
image_file= File(BytesIO(response.content), filename= "name.png")
valid perch
#

Make a redis cache or whatever, some form of abc for it to implement

burnt ether
#

@valid perch ohmy its u ❤️

valid perch
#

Storing everything in memory also works great scaling, but eh. Python and scale is fun

pliant gulch
#

wouldn't that mean all users who use the wrapper and want caching need to manually setup a redis cache

#

unless you use dockerfile to do it for you

valid perch
#

A redis cache would also allow for a distributed cache across shards and clusters n such

#

Sorry, this is being taken wrong. I meant have the option for a redis cache not force everyone to use it

#

For the people who want to scale and have big bots the option for a shared redis cache could be a nice alternative to storing everything in memory and requiring duplication across shards / clusters

valid perch
#

Anyway im off

river walrus
pliant gulch