#discord-bots

1 messages · Page 463 of 1

lusty swallow
#

you have a question @distant tree ?

#

missing permission

#

share the whole traceback

#

@slate swan

#

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

soft radish
#

how can i give everyone a role, like mass role or smtng

slate swan
#

how to add uptime of discord bot

#

??

#

anyone

soft radish
#

watch it

dapper cobalt
soft radish
#

should i define guild?

#

or no

reef shell
#

your bot will probably get rate limited

dapper cobalt
#

If it's where the command is used then ctx.guild.

reef shell
#

you can use await asyincio.sleep() to get rid of this

dapper cobalt
reef shell
#

same

fading harness
#

how to kick/ban/making invites in python?

dapper cobalt
lusty swallow
dapper cobalt
reef shell
#

dyno took 6+ hours for my 20k members server

soft radish
lusty swallow
soft radish
#

its better for mass roles

reef shell
#

at the same time lol

dapper cobalt
#

It's not "better", it's just which one sleeps less, and how many members you have.

soft radish
lusty swallow
#

Assuming there 20,000 member, and rate limit at 50 call per minute. That's 400 minute
That's bad especially if you want the bot to do stuff.

use multiple bots
like 10 of them communicating with each other to add role

reef shell
#

for m in guild.members

dapper cobalt
#

Python is just English in a snake way.

soft radish
#

o

#

i forgot to remove s

dapper cobalt
#

Invalid syntax, learn Python.

soft radish
#

forgot python now

#

sheesh

lusty swallow
#

that's super awful

soft radish
reef shell
#

again i used both

keen talon
hasty iron
#

they said bad lol

keen talon
#

!botvar

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!

hasty iron
#

yeah sure man try adding roles to 21k people and not get ratelimited

lusty swallow
#

use parallel processing for those type of commands @reef shell

multiple bots = more rates

hasty iron
#

what

lusty swallow
#

idk about global rate limit tho

hasty iron
#

multiple bots??

lusty swallow
#

why not

reef shell
#

idk man , both of the bots maybe got rate limited, and took more time than ETA

lusty swallow
#

isn't rate limit computed in a per bot basis?

hasty iron
#

the idea is just dumb

slate swan
hasty iron
#

no its token based

keen talon
#

||
How to cope with Alzheimer's disease
Step 1: Always write things done
Step 1: Always write things done
Step 1: Always write things done
Step 1: Always write things done
||
XD

hasty iron
#

well how are you exactly going to split the tasks

reef shell
lusty swallow
hasty iron
#

asyncio with threads is a big no go

dapper cobalt
#

Dyno has over a hundred shards.

lusty swallow
hasty iron
#

???

#

ok dude

#

you’te going to use aiohttp

wispy sequoia
#

does anyone know how to make a play music command? I've tried so many times and still can't do it

hasty iron
#

which internally uses asyncio.open_connection

wispy sequoia
#

ye

slate swan
#

try youtube_dl

wispy sequoia
#

like rythm

wispy sequoia
soft radish
dapper cobalt
#

!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)
soft radish
#

see

#

I can make music bot tho

reef shell
#

dpy handles rate-limits by default , doesn't it?

lusty swallow
wispy sequoia
hasty iron
#

that’s like pointless

#

why not a single bot??

soft radish
#

define music as music = DiscordUtils.Music()

hasty iron
#

there are ways to counteract ratelimits

soft radish
#

and so on

dapper cobalt
#

Imo, you can set a maximum amount of members that the bot can purge add roles to. If the amount is more than the maximum, either return an error, or just do it with the maximum amount.

lusty swallow
hasty iron
#

why

soft radish
#

there are tutorial at youtubes if im not mistaken

wispy sequoia
lusty swallow
hasty iron
soft radish
wispy sequoia
#

how

soft radish
hasty iron
#

read source code

soft radish
#

It's DiscordUtils tho

hasty iron
#

??

soft radish
#

but thats the method I used anyways

hasty iron
#

it doesn’t matter

dapper cobalt
#

Even if it does not use youtube_dl specifically, it still takes content from YouTube in a way that breaks their ToS.

lusty swallow
#

ytdl is usually against tos

slate swan
wispy sequoia
reef shell
wispy sequoia
#

lol

soft radish
#

theres at youtube

#

cant help since its a ytdl

wispy sequoia
soft radish
hasty iron
#

yeah sure, let you use other people’s videos without their permissions

wispy sequoia
#

ye

lusty swallow
#

youtube doesn't care usually

hasty iron
#

what

soft radish
hasty iron
#

they do care

#

it’s a law

soft radish
#

yep

reef shell
#

yes and groovy devs didn't want to pay fines

lusty swallow
wispy sequoia
#

well a spotify bot is ok then?

hasty iron
#

spotify doesn’t allow streaming

wispy sequoia
#

heh

hasty iron
#

nor any other platform

reef shell
wispy sequoia
#

so music bots will never exist anymore on ds?

hasty iron
#

why do you even need music bots

lusty swallow
#

it will still do. Many people will keep breaking laws. That' why there's pirated movies

hasty iron
#

imo, they’re pointless

soft radish
#

anyone want some while reading? 🍿

dapper cobalt
#

In the future if you want a music bot then make it your own and only for yourself.

lusty swallow
dapper cobalt
#

Yeah, screw programming, music producing is the future. Cars will use musical notes as fuel.

reef shell
#

just use spotify :kekw:

hasty iron
#

who uses spotify, i use osu! for music

#

ok this getting pretty ot

reef shell
#

what is this again

lusty swallow
#

imagine music bot but only vlog musics on the background

dapper cobalt
#

People can instead make a bot that plays music only from No Copyright Sounds channel.

wispy sequoia
#

ye

lusty swallow
#

i can probably make that tho

lusty swallow
soft radish
#
for m in guild.members:
    await m.add_roles(role)
    await asyncio.sleep(5)``` @dapper cobalt this?
lusty swallow
#

incomplete traceback

dapper cobalt
#

Or "radio" bots that play music set by the developer of the bot so they can assure it doesn't break any copyright laws, and also it would be fun to listen to random music instead of having to keep setting certain songs.

dapper cobalt
lusty swallow
#

did you even read your own quetion?

hasty iron
#

by solving it

lusty swallow
#

Your traceback is incomplete. Please provide whole traceback for debugging purposes

hasty iron
#

how about you send the error

lusty swallow
#

this was your question right?

#

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

Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke      
    await ctx.command.invoke(ctx)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke     
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
```This is just half of the traceback.
Please provide the other half
soft radish
#
@client.command()
async def mass_role(ctx):
  guild = ctx.guild
  role = discord.utils.get(ctx.guild.roles, name="role name")
  for m in guild.members:
    await m.add_roles(role)
    await asyncio.sleep(3)``` @dapper cobalt funny how it only gave a role to a single member
lusty swallow
#
@client.command()
async def mass_role(ctx):
    guild = ctx.guild
    role = discord.utils.get(ctx.guild.roles, name="role name")
    async for m in guild.members:
        await m.add_roles(role)
```try this instead
dapper cobalt
#

Use try...except so if it couldn't add roles to the other it would pass.

lusty swallow
steep estuary
#

how can i check if a user have a role by if condition?

soft radish
lusty swallow
unkempt canyonBOT
#

class discord.AsyncIterator```
Represents the “AsyncIterator” concept. Note that no such class exists, it is purely abstract.

`async for x in y` Iterates over the contents of the async iterator.
soft radish
#
Ignoring exception in command mass_role:
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 "main.py", line 37, in mass_role
    async for m in guild.members:
TypeError: 'async for' requires an object with __aiter__ method, got list

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: TypeError: 'async for' requires an object with __aiter__ method, got list```
lusty swallow
#

not sure ngl i followed this

soft radish
lusty swallow
# soft radish where do u put except again ._.
@client.command()
async def mass_role(ctx):
    guild = ctx.guild
    role = discord.utils.get(ctx.guild.roles, name="role name")
    for m in guild.members:
        try:
            await m.add_roles(role)
            await asyncio.sleep(3)
        except:
            pass
```idk what error it produce so pass everythng
wispy sequoia
#

help

#

I'm making channel overwrites for mute role

#

but Idk how they're called

steep estuary
#

how i can check if a member have a role by if condition?

slate swan
#

Get a role object of the role you want to check
Then check if that role is in user.roles

wispy sequoia
slate swan
#

May you not spoonfeed?

steep estuary
#

?? this

slate swan
#

No

#

Get a role object

steep estuary
slate swan
#

Then check if the role is in user.roles

#

!d discord.Guild.get_role

unkempt canyonBOT
steep estuary
#

i have this

#

this my command take

slate swan
#

Then simply check if the role is in user.roles

steep estuary
#

why user?

slate swan
#

user.roles is a list of roles

#

Yeah then member.roles

#

Doesn't matter

steep estuary
#

if role in member.roles ??

slate swan
#

Basic python ¯_(ツ)_/¯

steep estuary
#

:/

#

k

slate swan
#

It is correct

#

Just it's basic Python, so you should know that without really asking

#

No omg

#

This is like completely wrong

heady crescent
#

Hi!
So i'm trying to make an embed command and it gets a data from api and .txt file
And it's a lot of data that it gets and it's more than 4096 character

So is there's any way to make the bot send another message if the first message reached the limit aka 4096 character ?

slate swan
#

No line is close to correct

heady crescent
slate swan
#

I believe it's built-in.

ionic wadi
#

@bot.listen()
async def on_message(message):
if any(word in message.content.lower() for word in blacklist):
await message.delete()
await message.channel.send(f"{message.author.name}, Dat woord is niet toegestaan 😂 ")

I want It to see capitalized letters too, but they dont notice them.

heady crescent
slate swan
#

No, look how the code works

#

Then you will understand

heady crescent
#

now i understand thanks pepeprayge

wispy sequoia
#
f"Channel overwrites successfully created in `{(len(ctx.guild.text_channels) + len(ctx.guild.voice_channels))}` channels, with `test` skipped channels."```
I want to make **test** become the channels not overwrited. How?
steep estuary
#

is on_member_join inbuilt command?

slate swan
steep estuary
#

oo that only i meant

wispy sequoia
ionic wadi
#

@bot.listen()
async def on_message(message):
if any(word in message.content.lower() for word in blacklist):
await message.delete()
await message.channel.send(f"{message.author.name}, Dat woord is niet toegestaan 😂 ")

How can I make It recognize capital letters either?

slate swan
ionic wadi
#

But It doesnt recognize full capitals?

slate swan
#

It does?

#

Lower the message and the blacklist

wispy sequoia
slate swan
#

Write your blacklisted words in lower case and works fine

ionic wadi
#

I have that rn but If I send one of the blacklisted words

Like I have hi blacklisted
If I send HI It ignores It.

slate swan
#

It doesn't

#
message = "HI"
blacklist = ["hi"]

if any(word in message.lower() for word in blacklist):
    print("yes")

Prints 'yes', which is exactly what you've described above

soft radish
#

it only give the role to itself

slate swan
#

Do you have the members intent enabled?

soft radish
#

OH

#

SHI

boreal ravine
#

what

lusty swallow
#

Lol

wispy sequoia
#

how do I check if it's not a member?

#

example

#

kick vbkervbrv

bot: this is not a valid user

slate swan
#

It's done automatically if you type hint a member

#

There will be an error thrown

wispy sequoia
#

nothing's getting said

#

neither in console

lament mesa
#

That will raise commands.MemberNotFound

dapper cobalt
#

client.get_user(_id) returns None.

#

No. It's not a code problem.

lament mesa
#

Try using client.fetch_user

chilly fossil
#

Hi

#

ye

#

im indian

#

lol

lament mesa
#

line 18

chilly fossil
#

Nah

#

Ye

#

my real name is SIDDHANT

#

i changed it forreall

#

yea

#

oh lol i see

#

i thought no one kept their discord name as real name

#

yes :/

slate swan
slate swan
#

whats the problem?

#

There's an 'error' section, and it has already been answered I think?

#

what is leaderborad @slate swan

#

can you give me an example of that?

slate swan
#

can you give me an example of that?

#

And what do you get when using fetch_user then?

#

i mean can you give me an example of how the dict looks like
i believe your using the wrong key/value in get_member

#

Your issue is that the user with the ID is not being found

#

Eventually print the ID you're gathering from the file

elder python
#

what commands will stop working after the discord slash command update?

slate swan
slate swan
#

they have leaderboard[total_amount] = name,, where does leaderboard[amt] come from?

elder python
slate swan
#

Every single command won't work anymore

#

As simple as that

elder python
#

oh wow

slate swan
#

Use slash commands

elder python
#

no documentations

slate swan
#

Or eventually use the bot's mention as prefix, since bots will be able to read message contents from messages where they're mentioned

#

But it's a bad workaround

elder python
#

oh

slate swan
#

Or ask for the message intent

#

the on_message event will completely break, talk about leveling bots

#

If you have a use case

ionic wadi
#

File "/home/container/bot.py", line 165
embed=discord.Embed(title="Poll!", description=vraag)
TabError: inconsistent use of tabs and spaces in indentation

But why?

slate swan
#

Fix the indentation

#

Only use tabs or spaces

#

Don't mix

gritty flame
slate swan
#

or

#

You can always use spaces if you want

gritty flame
#

unless yk how much space a indention yas

ionic wadi
#

so embed=discord.Embed(title="Poll" description=vraag)

#

Huh that cant be

slate swan
#

That's not the issue

ionic wadi
#

Oh tabs

ionic wadi
waxen granite
#

File "D:\Discord Bot\ecrpgbot1-main\cogs\admin.py", line 67, in setname logChannel = self.bot.get_channel(id) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 793, in get_channel return self._connection.get_channel(id) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 1118, in get_channel pm = self._get_private_channel(id) File "C:\Users\Endomorph\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\state.py", line 329, in _get_private_channel value = self._private_channels[channel_id] TypeError: unhashable type: 'dict'

#

what is the problem here?

bitter depot
#

id is a dictionary rather than an integer @waxen granite

waxen granite
#

ah

#

guild = str(ctx.guild.id) try: id = self.guilddata[guild]["logs"] except KeyError: id = {} logChannel = self.bot.get_channel(id)

#

how to fix this?

bitter depot
#

The issue seems to be the KeyError section

#

id = {} is going to assign the id to an empty dictionary

#

I'd assume that if the id isn't already configured you'd either return (stop running the function) or use ctx.channel.id or something

waxen granite
#

hm

#

okay ty

boreal ravine
#

hm

steady flume
#

Guys, my bot turned off on heroku, is it normal ?

slate swan
#

Yes

steady flume
#

On website in resources it’s ON

slate swan
#

Because Heroku is bad for hosting

steady flume
slate swan
#

Limited hours of uptime per month etc.

steady flume
#

🤔🤔

steady flume
slate swan
#

You should not use Heroku to host your bot.

  • Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.

  • Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.

  • Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.

  • Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)

  • Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.

slate swan
steady flume
#

Hmhmhmhm

hasty iron
#

heroku is not for discord bots

#

its for web apps

steady flume
#

@slate swan which best hosting then ? Better free

slate swan
#

If you want a reliable and good hosting then pay the $2 per month or something

steady flume
#

Hmhmhm

#

Say then

#

I will think

#

@slate swan which is best ?

#

Or goood

slate swan
#

Remember that there is never the best of something

#

Take a look at this

steady flume
#

Haha, oke

vestal owl
#
if message.content.lower() == 'y':
        print('working')
if message.content.lower() == 'n':
    print('deleting..')
else:
    while True:
        print('moving back up to "working"')```
So what I'm trying to do is if the user does not type `y` or `n`, I'm trying to make the code go back up, and print `working` but it isn't doing that, anyone got any ideas?
storm zodiac
#

someone help me with todo commands 😕 i'm confused

slate swan
#

Show your current progress maybe

steady flume
#

@slate swan which hosting do u use ?

slate swan
#

We won't code for you

slate swan
steady flume
#

Idk

slate swan
#

Take the one you need

steady flume
#

Just interesting

steady flume
#

Ty bro

storm zodiac
# slate swan Show your current progress maybe
    # Todo
    @commands.group(name="todo", help="Will tell you, your todo list", invoke_without_command=True)
    async def todo(self, ctx):
        await ctx.trigger_typing()
        todo = await self.bot.db.fetch("SELECT task, position FROM todo WHERE user_id = $1", ctx.author.id)
        if len(todo) == 0:
            await ctx.send("You don't have a todo list\nTry to make one with `todo add` command")
        else:
            todombed = discord.Embed(
                title="Here is your todo list",
            )
            todombed.description = "\n".join("{position}: {task}".format(**_) for _ in todo)
            await ctx.send(embed=todombed)
    
    # Add
    @todo.command(name="add", help="Will add the given task", usage="<task>")
    async def add(self, ctx, *, task):
        await ctx.trigger_typing()
        await self.bot.db.execute("INSERT INTO todo(user_id, task) VALUES ($1, $2)", ctx.author.id, task)
        await ctx.send("Your task has been now added")```
#

the code is kinda fine, but the problem is, if 2 users does the todo add the number for their will be different

#

like
user#1:
2 - {task}

user#2:
1 - {task}
3 - {task}

#

the types for the columns btw:
user_id = Bigint
position = serial
task = text

slate swan
#

And let me guess, position is auto incrementing

storm zodiac
slate swan
#

There is your issue

#

You shouldn't auto increment it

upbeat otter
#

I am trying to make a calculator and when i try to press a button, it says, interaction failed, here is the current code

@client.command()
async def calc(ctx):
  m = await ctx.send(content="Loading Calculator")
  expression = "None"
  delta = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
  e = discord.Embed(title=f"{ctx.author.name}\'s calculator | {ctx.author.id}", description=expression, timestamp=delta)
  await m.edit(components=buttons, embed=e)
  while m.created_at < delta:
    res = await client.wait_for("button_click")
    if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
      expression = res.message.embeds[0].description
      if expression == "None" or expression == "An error Occurred":
        expression = ""
      if res.component.label == "Exit":
        await res.respond(content="Calculator Closed", type=7)
        break
      elif res.component.label == "←":
        expression = expression[:-1]
      elif res.component.label == "Clear":
        expression = None 
      elif res.component.label == "=":
        expression = cal(expression)
      else:
        expression += res.component.label
      f = discord.Embed(title=f"{res.author.name}\'s calculator | {res.author.id}", description=expression, timestamp=delta)
      await res.respond(content=None, embed=f, component = buttons,
      type=7)

slate swan
#

Shoud go in #databases as this is more related to database questions though

storm zodiac
#

like

slate swan
#

Then why saying that

storm zodiac
#

i said what is the problem, and gave you the whole code

slate swan
#

Nothing to do with the code

#

It's how you store the position integer

#

That is wrong

#

Maybe look how your database looks like and you will realize

storm zodiac
#

wdym how it looks ?

slate swan
#

Just

#

Look your database

#

Then you will understand by yourself

dense swallow
#

Does discord.TextChannel raise error when channel is not found?

slate swan
#

???

#

TextChannel is an object...

dense swallow
#

I meant if the mentioned channel does not exists, will it raise error

#

If so how can I modify it

slate swan
#

It will be None?

dense swallow
#

Is it HTTPException ?

slate swan
#

What are you trying

dense swallow
#

If that channel exists, send msg to that if that doesn't exist, send msg saying that channel does not exist

slate swan
#

Then get the channel and it will be none if channel not found

dense swallow
#

Ok

slate swan
#

Or just try to send

#

And it will raise HTTPException if it failed to send

hasty iron
#

you should use 2.0’s Views

#

it will make that alot easier

storm zodiac
slate swan
#

Just

#

Look your database

#

It's content

winter gull
#

hello,
uhh i am getting this error when i am trying to run a discord bot file

RuntimeError: Event loop is closed```
slate swan
#

Without code, we can't really help

steep estuary
#

how i can change registered help command in discord.py :/

#

i just want to change the look when author type >help

#

but i want >help [command] of that

#

:/

#

:/

slate swan
#

@steep estuary^

steep estuary
#
client = commands.Bot(command_prefix = '~', help_command=None)
```and this ?
#

@slate swan

slate swan
#

Can anyone here help me changing code to cogs please ping me

serene lynx
#

why is the emoji not sent?

unkempt canyonBOT
#

Hey @serene lynx!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

serene lynx
slate swan
#

Is the bot in the server where the emote is?

steep estuary
#

how i can add link with a name in an embed?

slate swan
#

Can anyone help

#

Can anyone here help me changing code to cogs please ping me

fickle turret
steep estuary
#

kk

steep estuary
slate swan
steep estuary
#

:/

#

:)

#

k

dapper cobalt
fickle turret
#

\:

steep estuary
#

srry :(

fickle turret
#

https://

dapper cobalt
#

Anyways let's not go ot.

slate swan
steep estuary
#

btw i use ":/" to show that i am confused and also to give u respect :(

#

:/

#

lol srry nvm

night onyx
#

Please tell me what's the problem in this code
Please ignore indentation

@bot.event
async def on_member_remove(member)
    await member.send("xyz")```
error
```Ignoring exception in on_member_remove
Traceback (most recent call last):
  File "C:\Users\GSSS OLWARA\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\GSSS OLWARA\Documents\Pikachu\cogs\welcome_leave.py", line 70, in on_member_remove
    await member.send(f"Hope You Had A Good Time In {member.guild.name} {member.name}")
  File "C:\Users\GSSS OLWARA\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "C:\Users\GSSS OLWARA\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 248, in request
    raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
dapper cobalt
#

If the member doesn't share any servers with the bot, the bot won't be able to send them messages.

serene lynx
#

@slate swan

calm vortex
#

Tried to customise Jishaku

boreal ravine
unkempt canyonBOT
reef shell
#

what is the difference between fetch_guild() and get_guild() ?

#

i'm using the latter one and it doesn't work the way i want

dapper cobalt
reef shell
dapper cobalt
#

I think that happens automatically.

#

I'm unsure if you can do it manually.

reef shell
#

oh then i have to use the api call method :sad:

slate swan
#

guys i want this command to work like that

+dm (user) (message) and it dms only me how can i do it



@bot.command()
async def dm(ctx, msg=None):
     await ctx.author.send(msg)  


dapper cobalt
#

Pass member before msg and type hint it with discord.Member.

hallow wigeon
#

you are not accepting the user in the args

slate swan
#

like how can i do it

hallow wigeon
#
@bot.command()
async def dm(ctx, user: discord.Member, msg=None):
     await user.send(msg)
#

¯_(ツ)_/¯

hasty iron
#

naming a Member object user pithink

hallow wigeon
hasty iron
#

and that can error

#

you cant send None

hallow wigeon
#

yea

#

default to some other string

heady crescent
#

is there's a way that pillow get image asset from a website ?

hasty iron
#

send a GET request to the url

#

and read the contents as bytes

heady crescent
#

thanks

slate swan
#

How to add cooldowns to commands?

#

hey guys, is herokus postgresql a good db?

cloud dawn
#

I have been summoned, altough it's on a weekend so i won't be on at that time lol.

reef shell
#

use this command deco

#

and also import the BucketType

slate swan
dapper cobalt
unkempt canyonBOT
#

discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/stable/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/stable/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

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

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

How to set a message that its a cooldown and the command can be accessed agian in for example 2 minutes

dapper cobalt
#

!d discord.ext.commands.CommandOnCooldown

unkempt canyonBOT
#

exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after)```
Exception raised when the command being invoked is on cooldown.

This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
cloud dawn
#

We do python here

hoary gust
#

@cloud dawn for frontend bud

#

Python for backend

cloud dawn
#

front-end is either html,css,js or any framework of that.

lament mesa
#

||brython||

cloud dawn
slate swan
#
import discord
from discord.ext import commands
import BucketType

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

@client.event
async def on_ready():
  print("Bot is ready")

@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
  await ctx.send("test")
``` how long would this be for?
fickle turret
slate swan
#

per user

novel rampart
#

what is the error

slate swan
#

How to add an error message to it? Like You can only use this every 5 seconds. You need to wait 3 seconds more.

slate swan
novel rampart
#

i am swiching my bot to haruqu i am deleting my account

novel rampart
slate swan
#

Then?

novel rampart
#

ok one sec

novel rampart
#

i don't understnd that error

#

@slate swan

cloud dawn
slate swan
#

What you didn't understand?

cloud dawn
#

!d discord.on_command_error

unkempt canyonBOT
#

discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
slate swan
#

"Improper token has been passed"

novel rampart
cloud dawn
#
bot.run('Improper token')
``` Now the error makes sense
novel rampart
#

discord.errors.LoginFailure: Improper token has been passed.

novel rampart
boreal ravine
cloud dawn
boreal ravine
novel rampart
slate swan
boreal ravine
#

It's self explanatory

cloud dawn
fickle turret
novel rampart
#

then how i improve my Improper token

boreal ravine
novel rampart
#

yes

slate swan
# cloud dawn This raises an exception `commands.CommandOnCooldown`
import discord
from discord.ext import commands
import BucketType

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

@client.event
async def on_ready():
  print("Bot is ready")

@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
  try:
    await ctx.send("test")
  except commands.CommabdOnCooldown(cooldown, retry_after):
    await ctx.send(f"On cooldown! Use agian after: {retry_after} seconds.")
```?
cloud dawn
boreal ravine
fickle turret
#

Oh url argument

boreal ravine
slate swan
boreal ravine
fickle turret
#

I forgot about that, thought you meant that in []() format

cloud dawn
#

Me too 😓

slate swan
boreal ravine
#

ok.

fickle turret
slate swan
cloud dawn
slate swan
#

Where

lament mesa
cloud dawn
novel rampart
#

ok it have solved

#

my stupiid

#

i am is and stupid

slate swan
#
import discord
from discord.ext import commands
import BucketType

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

@client.event
async def on_ready():
  print("Bot is ready")

@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
  await ctx.send("test")
@client.event
async def on_command_error(ctx, error: commands.CommandOnCooldown(cooldown, after)
  await ctx.send(f"Can be used agian after {after} seconds.")
``` like this?
boreal ravine
lament mesa
#

whats that typehint

heady crescent
#

Hi
So i was trying to use pillow to make a command and everything was working fine but now i've got an error

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/track.py", line 668, in add
    data = BytesIO(await asset.read())
  File "/home/container/.local/lib/python3.9/site-packages/PIL/Image.py", line 546, in __getattr__
    raise AttributeError(name)
AttributeError: read

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

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/track.py", line 275, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.9/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: read```

> This is the image code
```py
  file = Image.open("trackeradd.png")
  asset = Image.open(BytesIO(headreq.content))
  draw = ImageDraw.Draw(file)
  font = ImageFont.truetype("mc.ttf", 24)
  draw.text((0,150), name, (0, 0, 0), font=font)

  data = BytesIO(await asset.read())
  head = Image.open(data)
  head = head.resize((185, 185))

  file.paste(head, (1241, 140))
  file.save("added/added.png")```
cloud dawn
heady crescent
cloud dawn
#

Just because you are using it inside your discord bot doesn't automatically make it related to discord.

slate swan
boreal ravine
slate swan
#

Okay

cloud dawn
boreal ravine
lament mesa
#

no

#

after is not defined

boreal ravine
hasty iron
cloud dawn
#

He has the same.

slate swan
#

I defined it in (cooldown, after)

boreal ravine
#

o

lament mesa
#

you havent defined it

cloud dawn
slate swan
# lament mesa you havent defined it
import discord
from discord.ext import commands
import BucketType

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

@client.event
async def on_ready():
  print("Bot is ready")

@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
  await ctx.send("test")
@client.event
async def on_command_error(ctx, error: commands.CommandOnCooldown(cooldown, retry_after)
  await ctx.send(f"Can be used agian after {retry_after} seconds.")
``` like this?
lament mesa
#

no

#

you will have to use isinstance and check the exception

slate swan
#

What

lament mesa
boreal ravine
#

you can also just send the error without isinstance

maiden fable
unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3.10/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3.10/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union).
maiden fable
#

It checks of an object is an instance of a class

boreal ravine
#
@client.event
async def on_command_error(ctx, error):
  error=discord.Embed(title='Error', description=error)
``` this mine :)
lament mesa
slate swan
#

Who from Indian here .

boreal ravine
#

use instance then

slate swan
#
import discord
from discord.ext import commands
import BucketType

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

@client.event
async def on_ready():
  print("Bot is ready")

@client.command()
@commands.cooldown(rate=1,per=5,type=BucketType.user)
async def test(ctx):
  await ctx.send("test")
@client.event
async def on_command_error(ctx, error):
  if isinstane(error, commands.CommandOnCooldown):
    await ctx.send(f"Can be used agian after {error.retry_after} seconds.")
``` like this?
maiden fable
#

No

slate swan
#

Whats wrong with that one

spring flax
#
if isinstane(error, commands.CommandOnCooldown):
#handle it
maiden fable
#

Yea

slate swan
#

I did so

spring flax
#

Nope

#

look at your if isintance line

slate swan
#

I have (cooldown, after)

spring flax
#

remove cooldown, retry_after from that line

slate swan
#

But how to see how much time its left then

spring flax
spring flax
slate swan
#

How

lament mesa
#

error.retry_after

spring flax
#

yeah

#

and probably round it or put it to specific decimal places

spring flax
#

yes

slate swan
#

Oh

#

It is?

spring flax
#

yep

slate swan
#

Oh

#

Cool

#

Thanks!

#

Can I format the error.retry_after so it says in hours and minutes instead?

spring flax
#

and sure you can do that

gloomy coral
#

Hi. I have made my bot.py cooler, care to see it and help me improve it?

#

And check it, cuz idk if it works

spring flax
#

uh

gloomy coral
gloomy coral
#

xD

lament mesa
#

the imports...

jade jolt
#

oh god

soft imp
#

need help

#

are people still here?

#

bruh

gloomy coral
slate swan
# gloomy coral Hi. I have made my bot.py cooler, care to see it and help me improve it?
  • Imports can be more cleaner
    • Categorize them like inbuilt packages at starting, discord and pil ones at second block, and your bot's files at the last
    • Just do from Foo import bar, baz, idk, no need to separate them in separate lines.
  • For data which needs to be accessed very frequently (like prefix), it's good to cache it instead calling Database on every event
  • bot.remove_command('help')....
  • Some line spacing
  • Instead of overwriting events, I prefer to use listeners, but doesn't really matter much
  • PEP8 👀
lament mesa
gloomy coral
slate swan
#

You read that very quick

gloomy coral
#

other thn imports

#

cuz imports are gonna be replaced by 2 3

#

as cogs do the work

soft imp
lament mesa
gloomy coral
gloomy coral
soft imp
#

hello pls help me

slate swan
lament mesa
soft imp
#

how do you make an anti-spam bot pls

gloomy coral
lament mesa
soft imp
#

oh my goddd

#

someone help

slate swan
lament mesa
unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

gloomy coral
#

oh alr

soft imp
#

i have searched the world for help

#

help

gloomy coral
soft imp
#

i dont understand it

gloomy coral
#

but everything else should work right? Nothing wrong... Also how is it

gloomy coral
slate swan
#

store them in dict

gloomy coral
slate swan
#

there are million ways to cache

gloomy coral
#

and more efficient

slate swan
#

Ah I think you didn't get what is cache.

gloomy coral
#

plus when the bot goes offline

#

vars reset

soft imp
#

bruh cant you make me understand it

#

pls 😢

slate swan
lament mesa
slate swan
gloomy coral
#

also @lament mesa nice.... i saw

#

orm, ill use it when u r done with it

lament mesa
#

lemon_pleased Thanks

slate swan
gloomy coral
slate swan
#

How to make click text?

gloomy coral
#

?/

fiery rain
soft imp
buoyant ore
#

how to make anti-spam bot in discor.py help pls

slate swan
#

Btw, is it possible to cache your main app stuff in cython?

buoyant ore
#

pls

fiery rain
#

pls

soft imp
#

pls

slate swan
#

pls

buoyant ore
#

lol

fiery rain
#

lol

soft imp
#

lol

slate swan
#

Uh why y'all having same messages, sus

#

lol

gloomy coral
#

is there a way to make link look like smth else, go somewhere else

buoyant ore
#

idk tbh

fiery rain
#

idk tbh

soft imp
#

idk tbh

slate swan
#

idk tbh

gloomy coral
#

😦

fiery rain
#

just help me

soft imp
#

just help us

blazing vapor
lament mesa
buoyant ore
#

pretty pls

fiery rain
#

imma go nobodys being helpful

buoyant ore
#

me too

blazing vapor
soft imp
slate swan
#

How to make click text? Like click on text and it becomes a link

#

just pip uninstall <package>?

soft imp
lament mesa
#

bruh, i sent a link to a project, check it

soft imp
#

i didnt understand it

elfin merlin
slate swan
#

Please put your efforts to read it atleast, what you didn't understand?

soft imp
#

k thx ill try

gloomy coral
#

So i have a discord bot, where im plotting some data of my bot on a graph. problem is, its deployed on a vps. How can i see the graph live on my pc?

slate swan
#

Matplotlib?

lament mesa
#

Make the bot send the graph

soft imp
#

i didnt work guys

#

oh wait theres error

#
Traceback (most recent call last):
  File "C:\Users\*\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\*\Documents\Stuuf\botol.py", line 30, in on_message
    if authors[author_id] > 5:
KeyError: 881537676094881793
lament mesa
#

that key doesnt exist

soft imp
#

how do you know

slate swan
#

👀

#

Because you just copied a non-working code from stackoverflow question

soft imp
#

oh

#

but @lament mesa gave it to me

lament mesa
#

i didnt send a stackoverflow link

slate swan
#

The error is exactly same as the user who asked that question on sof

lament mesa
#

Copy and paste it ez

#

Install the package

soft imp
#

with pip install antispam

lament mesa
#

no

#

the instructions are there in the pypi page

soft imp
#

ok but i nstalled and got error

#
    from antispam import AntiSpamHandler
ImportError: cannot import name 'AntiSpamHandler' from 'antispam' (C:\Users\*\AppData\Local\Programs\Python\Python39\lib\site-packages\antispam\__init__.py)
[Finished in 817ms]
#

hello

#

do you knwo answer

calm vortex
#

Anyone?

soft imp
#

nope

#

soz 😦

lament mesa
#

Did you install it properly?

#

How did you install it

#

bruh

soft imp
#

wat

lament mesa
#

thats not the proper package name

soft imp
#

whats it called

lament mesa
#

the instructions are right there in the web site

soft imp
#

k i did it

#

is there something wrong with this

#
@client.command()
async def sue(ctx, member : discord.Member):
  money = random.randrange(50001)
  description = [f"You took {member.mention} to court and sued hime of {money}",
  f"You took {member.mention} to court but the judge found no dirt on him lol"]
  ok = random.choice(description)
  beddy = discord.Embed(title=f"Attempting to Sue {member}...", description=f"{ok}", color = discord.Colour.purple())
  await ctx.send(embed=beddy)
#

hello?

#

@lament mesa

turbid pivot
#
@client.command(aliases=['tm'])
async def tempmute(ctx, member: discord.Member, time: Union[int, str] = 0, *, reason=None):
    guild = ctx.guild

    mutedRole = discord.utils.get(guild.roles, name="Muted")

    if not mutedRole:
      mutedRole = await guild.create_role(name="Muted")

    for channel in guild.channels:
        await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)

        embed = discord.Embed(title="muted!", description=f"{member.mention} has been tempmuted ", colour=discord.Colour.light_gray())
        embed.add_field(name="reason:", value=reason, inline=False)
        embed.add_field(name="time left for the mute:", value=f"{time}{0}", inline=False)
        await ctx.send(embed=embed)

        if 0 == "s":
                await asyncio.sleep(time)

        if 0 == "m":
                await asyncio.sleep(time*60)

        if 0 == "h":
                await asyncio.sleep(time*60*60)

        if 0 == "d":
                await asyncio.sleep(time*60*60*24)

        await member.remove_roles(mutedRole)


        return```
#

is there something wrong?

#

it is not adding muted role to the member 😦

maiden fable
calm vortex
#

Nah I had to do bot=bot in CustomJishaku(), as it's a kwarg

maiden fable
#

Ah, ok

sudden magnet
#

Does anyone using D.py know if their is a close event for cogs?

maiden fable
#

Wym?

sudden magnet
#

with bot I can do ```python

async def close(self) -> None:
    print(f"[EXIT  ] Shutting down...")
    await super().close()
lament mesa
#

!d discord.ext.commands.Cog.cog_unload

unkempt canyonBOT
#

cog_unload()```
A special method that is called when the cog gets removed.

This function **cannot** be a coroutine. It must be a regular function.

Subclasses must replace this if they want special unloading behaviour.
ornate scarab
#

Hi guys, can the bot accept attachments sent to it? For example pictures

My code:

@bot.listen("on_message")
async def log_message(message):
    channel = bot.get_channel(bot_msg_log_channel)
    if message.guild is None and not message.author.bot:
        embed = discord.Embed(
            description = f'Author: {message.author.mention}\n\n'f'Msg:\n'f'{message.content}',
            color = 0x0068c9
            )
        embed.set_thumbnail(url=message.author.avatar_url)
        await channel.send(embed=embed)

But if they send a picture or something attachment, just an empty message comes

maiden fable
#

!d discord.Message.attachments

unkempt canyonBOT
lone aurora
#

for msg sender would it be ctx.author.message?

lament mesa
#

no

#

ctx.message.author

#

or ctx.author

lone aurora
#

but that shows the author

#

not his msg

#

like
seatch : hi

ctx.message.author = seatch
hi = ?

#

@lament mesa any clue mate?

lament mesa
#

if you want to get the message it will be ctx.message

lone aurora
#

ah ok thanks

turbid pivot
#

Oh

turbid pivot
lament mesa
#

the integer 0 will never be equal to a string

lone aurora
#

!d discord wait_for

#

heh

ornate scarab
supple storm
#
@client.command(name = "exp")
async def exp(ctx,user : discord.User = None):
    if ctx.author.bot:
        return
    elif not user:
        abc = ctx.author.id
        cursor = levelsystem.cursor()
        cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
        result = cursor.fetchall()
        currentxp = result[0][0]
        await ctx.message.reply(f"{ctx.message.author.display_name}#{ctx.message.author.discriminator} Has {currentxp} XP !")
    else:
        abc = user.id
        cursor = levelsystem.cursor()
        cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
        result = cursor.fetchall()
        currentxp = result[0][0]
        await ctx.message.reply(f"{user.display_name}#{user.discriminator} Has {currentxp} XP !")
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "exp" is not found

why

#

although i change the code into pass and the result is same

leaden ginkgo
#
@client.command()
async def get_author(ctx, msg_id: int):
    msg = await ctx.channel.get_message(msg_id)
    await ctx.send("The author is %s" % msg.author)```Alternative or no ?
steep estuary
#

how to make bot reply like this

turbid pivot
lament mesa
turbid pivot
lament mesa
steep estuary
turbid pivot
steep estuary
lone aurora
#
    if msg.content.startswith('abcidc'):
        channel = message.channel
        await channel.send('Enter the news')```
#

this should work in on_message event right?

lone aurora
#

then why isnt it ._.

spring flax
lament mesa
#

int != str

turbid pivot
steep estuary
turbid pivot
lone aurora
#

File "C:\Users\HP\Desktop\dc bot\main.py", line 33, in on_message
channel = message.channel
AttributeError: module 'discord.message' has no attribute 'channel'

lament mesa
unkempt canyonBOT
#

@lament mesa :white_check_mark: Your eval job has completed with return code 0.

False
supple storm
leaden ginkgo
#

But how can i do

lament mesa
#

channel.fetch_message

leaden ginkgo
#

Hmm

supple storm
#
@client.command()
async def hello(ctx):
    pass
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "hello" is not found

what

supple storm
steep estuary
spring flax
steep estuary
#

np

slate swan
turbid pivot
supple storm
#

no i tried to add some codes into it but it not work

turbid pivot
#

What were the codes ??🤨

supple storm
#

await ctx.send("OK")

spring flax
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.

steep estuary
slate swan
supple storm
#

!paste

@client.command()
async def hello(ctx):
    await ctx.send("OK")
slate swan
#

try checking the docs

supple storm
#

it not work

spring flax
#

what

turbid pivot
#

Ig it is right

spring flax
#

no

turbid pivot
#

Hmm

spring flax
#

async def on_message is an event

slate swan
#

that is not correct

turbid pivot
#

I m new

supple storm
#

no i add my prefix

slate swan
#

Lmao noo

supple storm
#

i tried

shy schooner
#

you must pass message instead of 'hello'

slate swan
#

also its a command

spring flax
#

don't use that on_message for commands anyway

slate swan
supple storm
#

i dont need it

slate swan
#

f my nitro ended

supple storm
#

my whole code is very ez

#

but it said that command hello is not found xD

kindred epoch
slate swan
#

bre

supple storm
#

i know it

supple storm
slate swan
#

client.run is suppose to be in the bottom of the code after everything else

#

not before the command

#

heh?

boreal ravine
#

^

#

it wont register the command if you run the bot before inserting the command

valid galleon
#

So im using praw to get posts from a subreddit, and i always get this prompt when someone uses the command. now, i did try to move to asyncpraw as its faster, but i was getting a few errors, so i moved back to praw, and i dont want this to show in the terminal:

It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.```
lament mesa
#

bot.run blocks mhm

#

!d discord.Client.run

unkempt canyonBOT
#

run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.login "discord.Client.login").

Roughly Equivalent to...
lament mesa
#

A blocking call that abstracts away the event loop initialisation from you.

slate swan
#

then use asyncpraw

valid galleon
supple storm
#
def generateXP():
    return random.randint(1,5)

@client.listen('on_message')
async def on_message(message):
    if message.author.bot:
        return
    elif message.content.lower() == "!exp":
        pass
    else:
        xp = generateXP()
        cursor = levelsystem.cursor()
        cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = " + str(message.author.id))
        result = cursor.fetchall()
        if (len(result)) == 0:
            cursor.execute("INSERT INTO levelsystem VALUES(" + str(message.author.id) + "," + str(xp) + ")")
            levelsystem.commit()
            await message.reply("Done")
        else:
            newXP = result[0][0] + xp
            cursor.execute("UPDATE levelsystem SET userxp = " + str(newXP) + " WHERE client_id = " + str(message.author.id))
            levelsystem.commit()
            await message.reply("Done")
    
@client.command()
async def exp(ctx,user : discord.User = None):
    if not user:
        abc = ctx.author.id
        cursor = levelsystem.cursor()
        cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
        result = cursor.fetchall()
        currentxp = result[0][0]
        await ctx.message.reply(f"{ctx.message.author.display_name}#{ctx.message.author.discriminator} Has {currentxp} XP !")
    else:
        abc = user.id
        cursor = levelsystem.cursor()
        cursor.execute("SELECT userxp FROM levelsystem WHERE client_id = {str(abc)}".format('peepeepoopoo'))
        result = cursor.fetchall()
        currentxp = result[0][0]
        await ctx.message.reply(f"{user.display_name}#{user.discriminator} Has {currentxp} XP !")

it recognized !exp as in on_message

kindred epoch
slate swan
#

try putting print('works') before and after everything you do in the command you can find out where it gone wrong

supple storm
lone aurora
#
@client.command(aliases=['ac'])
async def announce(ctx, message):
    embed = discord.Embed(
        title = '',
        description = '',
        colour = ctx.author.colour  
        
    )

    embed.set_footer(text='By oSeatch#6969')
    embed.set_author(name=ctx.message.author)
    embed.add_field(name='News', value=message , inline=False)

    await ctx.send(embed=embed)
    await ctx.message.delete()``` 

Im trying to make it embed the msg after the command so in

.announce `hi this is test`

This is a test should be embedded, i still dont get how i can do this though..
#

im always scrolling in here and see that i always ask for the most easiest stuff, other's people stuff so hard smh ._.

slate swan
#

maybe this?

@client.command(aliases=['ac'])
async def announce(ctx, message):
    embed = discord.Embed(
        colour = ctx.author.colour  
        
    )

    embed.set_footer(text='By oSeatch#6969')
    embed.set_author(name=ctx.message.author)
    embed.add_field(name='News', value=message , inline=False)

    await ctx.send(embed=embed)
    await ctx.message.delete() 
lone aurora
#

doesn't hurt trying

kindred epoch
#

idk why your deleting the message right after it sends it

slate swan
#

its Seatch's command

#

not mine

kindred epoch
#

ik wrong reply

supple storm
lone aurora
#

poggerss it works, thanks alot man

slate swan
lone aurora
#

i think it was because there was an error in the other part of the code

supple storm
lone aurora
#

so that means my original code might work too ._.

supple storm
#

and my code is right

#

my mysql database is updated

pliant gulch
slate swan
shell wing
#

im using cogs and so the cog reloading commands..can such command be used for a json file ???

lone aurora
#
@client.command()
async def purge(ctx, amount=5):
    if (not ctx.author.guild_permissions.manage_messages):
        await ctx.message.delete()        
        await ctx.send("This Command Requires A Higher Rank!")
        return
    if (ctx.author.guild_permissions.manage_messages):
        await ctx.channel.purge(limit=amount)
        await ctx.send(f"__**{amount}**__ messages have been removed.") 
        await ctx.message.delete()```

Here's my normal purge code, yeye everyone has it, simple stuff- now how can i make it so that after like 5 seconds of sending "Amount of messages have been removed" it get auto deleted, is it even possible?
lone aurora
#

i added it back and it worked

shell wing
lone aurora
#

the problem was that i made a mistake in the code and left broken code in there, that just didnt allow the rest of the code to work

shell wing
pliant gulch
#

In ctx.send it has a delete_after kwarg, you pass in 5 and after 5 seconds it gets removed

#

!d discord.abc.Messageable.send

unkempt canyonBOT
#

await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=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/stable/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/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
grim oar
#

git gud

shell wing
#

shhh python the lang is typing brainmon

grim oar
#

bad helper

lone aurora
pliant gulch
lone aurora
#

like "Message has been deleted", stays there for 5 seconds and gets deleted

grim oar
shell wing
shell wing
slate swan
#

i dont think json files can be reloaded

shell wing
lament mesa
#

what is reloading a file wot

pliant gulch
#

Write -> Save -> Load

lone aurora
still tiger
#

Hello everyone, I am trying to use slash commands but I am not able to, it just simply dosent show there. The normal command works fine, heres the code so can someone point out what wrong thing I did or how to fix the issue?

import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
from discord_slash import SlashCommand

load_dotenv('.env')

client = commands.Bot(command_prefix="sw:", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)

@client.event
async def on_ready():
    print(f"Bot activated.")
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="sw:help"))

@client.command(description="Sends bot's latency")
async def ping(ctx):
    await ctx.send('Pong! {0}'.format(round(client.latency, 1)))


@slash.slash(name="Ping", description="Sends bot's latency")
async def ping(ctx):
    await ctx.send('Pong! {0}'.format(round(client.latency, 1)))


client.run(os.getenv("TOKEN"))
shell wing
still tiger
#

You might mean appending to the json file

upbeat otter
#

Guys, i am trying to make a calculator, but when i click on a button, it says, interaction failed, Here is my current code


@client.command()
async def calc(ctx):
  m = await ctx.send(content="Loading Calculator")
  expression = "None"
  delta = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
  e = discord.Embed(title=f"{ctx.author.name}\'s calculator | {ctx.author.id}", description=expression, timestamp=delta)
  await m.edit(components=buttons, embed=e)
  while m.created_at < delta:
    res = await client.wait_for("button_click")
    if res.author.id == int(res.message.embeds[0].title.split("|")[1]) and res.message.embeds[0].timestamp < delta:
      expression = res.message.embeds[0].description
      if expression == "None" or expression == "An error Occurred":
        expression = ""
      if res.component.label == "Exit":
        await res.respond(content="Calculator Closed", type=7)
        break
      elif res.component.label == "←":
        expression = expression[:-1]
      elif res.component.label == "Clear":
        expression = None 
      elif res.component.label == "=":
        expression = cal(expression)
      else:
        expression += res.component.label
      f = discord.Embed(title=f"{res.author.name}\'s calculator | {res.author.id}", description=expression, timestamp=delta)
      await res.respond(content=None, embed=f, component = buttons,
      type=7)
still tiger
#

the full error message and line number it occured at?

shell wing
#

and like using the newly appened json file

still tiger
#

Are you making a copy of the json file and appending it there? just using it again will solve it

upbeat otter
still tiger
#

any error in your shell?

upbeat otter
upbeat otter
lone aurora
#

await ctx.send(f"__**{amount}**__ messages have been removed.", delete_after=300) umm this just doesn't show the msg has been removed anymore..

lone aurora
#

so i want it to show
"messages have been deleted"
and it stays there for 5 seconds, and gets deleted

upbeat otter
shell wing
#

how do i send a looped message to users in a json file ??

upbeat otter
lone aurora
#

oh so u re-purge it

upbeat otter
lone aurora
#

but if someone sends another msg

still tiger
#

I think he wants to use the delete after property instead

lone aurora
#

then it will just purge their msg

upbeat otter
lone aurora
#

yes

shell wing
lone aurora
shell wing
#

whats the error

lone aurora
#

it deleted the "Msgs have been deleted" itself

#

no error just that

upbeat otter
shell wing
#

then ? what do u need ?

shell wing
#

and thats what the code does..

lone aurora
#

sadness i try once more

lone aurora
#

i changed it later

#

i tried it with 5 seconds but it auto deletes

upbeat otter
lone aurora
#

bruh did i just-

#

if this works im hanging myself

shell wing
#

😑

upbeat otter
shell wing
#

u wanna delete the msg but no auto delete...

lone aurora
#

bruh i seriously.. it worked

shell wing
upbeat otter
lone aurora
upbeat otter
#

You have my last respects

shell wing
#

alr

lone aurora
#

scratch that, i wanna check out hell first

upbeat otter
compact field
#

hi guys how can i mention channel with bot ?

shell wing
boreal ravine
#

why so many indians

scarlet snow
#

How can I access discord.Role color?

#

oh wait just saw a property on it xD

turbid pivot
maiden fable
#

Lmao true tho

#

Yay

tulip oracle
#

is there an api for new post reddit events?
i normally just use the raw json for reddit but i couldnt automate this my self for new post i dont think

final iron
#

How would I make a command that sends how many times a certain word was said in a server

#

I'm guessing I would have to use on_message

#

I just have no idea how I would implement that with a command

dapper cobalt