#discord-bots

1 messages · Page 924 of 1

slate swan
#

how do i read the last 50 messages in a channel through my bot

flat solstice
#

It's the new way to start dpy bots based on dpys new asyncio changes

slate swan
unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") 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
#

thanks

cold sonnet
#

I could do this at 13

slate swan
hollow carbon
#

🥲😗🥺

cold sonnet
hollow carbon
cold sonnet
slate swan
#

imagine playing games wouldnt be me

#

but ngl coding is alot fun (and painful lmao)

slate swan
maiden fable
#

Try game deving, you will see how fun it is

cold sonnet
#

it is

cold sonnet
slate swan
junior verge
#

ImportError: cannot import name 'app_commands' from 'discord' uh

#
import discord
from discord.ext import commands
from discord import app_commands

class Ping(commands.Cog):

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

    @app_commands.command(name="ping", description="Returns the latency of the bot")
    async def ping(self, interaction: discord.Interaction):
        await interaction.response.send_message(f'Pong! **{round(self.client.latency * 1000)}**ms')

def setup(client):
    client.add_cog(Ping(client))
cold sonnet
#

yeah I don't think so either

#

wait

#

well the docs say it's there

hushed galleon
#

that means you need to upgrade your dpy

cold sonnet
#

the website docs

#

but not even the python bot knows about it

#

wassup with that

formal basin
#

When I run this command it sends 4 things but i only want it to send 1

hushed galleon
#

also setup() and add_cog have been changed to be asynchronous in the latest updates to dpy

cold sonnet
#

deindent the send line

#

take it outta the for loop

slate swan
cold sonnet
#

I'm gonna search up your messages and correct every single grammar mistake you've ever made on this server

#

nah jk

slate swan
stone beacon
#

🗿

cold sonnet
#

jkn't

cold sonnet
formal basin
cold sonnet
#

can't

#

doesn't

cold sonnet
formal basin
#

Oh

cold sonnet
#

did you do

#

won't, in

#

Imma stop

tidal hawk
#

Don't stop

cold sonnet
#

nah Imma stop

slate swan
#

how do i make a bot not add a field jf the user has no badges but add a field if the user has a badge

formal basin
cold sonnet
#

!d discord.Member.public_flags

unkempt canyonBOT
#

property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
cold sonnet
#

check if this is empty or not

cold sonnet
formal basin
slate swan
#

the docs don’t help

cold sonnet
#

just remove four spaces from the send line 😦

formal basin
#

Ok

cold sonnet
#

doesn't

slate swan
#

okay thanks

cold sonnet
#

just slang

formal basin
cold sonnet
cold sonnet
#

okimi you're being

#

sus

formal basin
cold sonnet
#

you removed like 8 spaces

formal basin
#

No I removed 4

cold sonnet
#

you're indenting with 2 spaces?

slate swan
cold sonnet
#

are u single too

formal basin
slate swan
cold sonnet
#

oh

slate swan
#

😳

cold sonnet
slate swan
formal basin
#

Ok

cold sonnet
#

it has to be on the same level as your for loop

final iron
slate swan
#

😏

formal basin
cold sonnet
#

technically

#

it should be undent

cold sonnet
slate swan
#

In embeds.0.fields.0.value: This field is required I'm still getting this error.

cold sonnet
#

oh there you go-o
can't make a field without a value

#

it doesn't rhyme :c

#

can't make a field without a value

slate swan
#

value=badgelist, is it because of this?

cold sonnet
#

if the list is empty

#

it's because of that

slate swan
#

what should i add into it then?

cold sonnet
#

value=badgelist if badgelist else "None"

slate swan
#
if user.public_flags:
        badgelist = ""
        if user.public_flags.hypesquad_brilliance:
            badgelist += f":brilliance: Hypesquad Brilliance\n"
        if user.public_flags.hypesquad_bravery:
            badgelist += f":bravery: Hypesquad Bravery\n"
        if user.public_flags.hypesquad_balance:
            badgelist += f":balance: Hypesquad Balance\n"

        e.add_field(
            name=f"**Badges**",
            value=badgelist if badgelist else "None",
            inline=False,
        )

    else:```
ive got this
cold sonnet
#

that's no list

#

this didn't fix it

slate swan
#

i dont get what you mean by list

cold sonnet
#

value=badgelist if badgelist != "" else "None"

#

the value is badgelist if badgelist isn't empty

#

else the value is None

slate swan
#

do i still need if user.public_flags:

cold sonnet
#

yeah ig

#

yeah

slate swan
cold sonnet
#

don't think there's a need to do that

slate swan
#

still doesnt work

slate swan
cold sonnet
#

he don't use a list

slate swan
#

in the badges field it just returns with :

#

!e py empty = "" if 1 == 1: empty += "2" print(empty) print(empty)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 2
cold sonnet
#

!e

empty = ""
for i in range(10):
    if i < 8:
        empty += str(i) + "\n"
print(empty)
unkempt canyonBOT
#

@cold sonnet :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
cold sonnet
#

there could be many stuff in public_flags

slate swan
#

ill just leave it outta my code

#

too hard

cold sonnet
#

hypesquad stuff

#

idk lmao

#

bot dev

slate swan
cold sonnet
#

public_flags is a list of badges

slate swan
#

i just want the hypesquad

cold sonnet
#

then your code should work fine

#

innit

slate swan
#

it doesnt

cold sonnet
#

why

#

what's the error or problem

slate swan
#

firstly i dont even know what should be in my code, you said about a list then said no, and im confused now

cold sonnet
#

there are always multiple ways to do something

slate swan
#

but i dont know what ways, thats why im asking

cold sonnet
#

you could make a list but then you'd have to join the elements

slate swan
#

but i dont know how to, that why im asking

cold sonnet
#

so a string is good

#

which you did

slate swan
#

ok

#

what next?

reef dock
#

in April with the new change to the message thing and bots have to move over to slash commands will all bots be affected or only verified bots?

reef dock
#

👌 thx for the answer

manic wing
unkempt canyonBOT
#

@manic wing :white_check_mark: Your eval job has completed with return code 0.

False
manic wing
#

comprehend

cold sonnet
#

what

#

doesn't matter

manic wing
#

badgelist if badgelist else "None"
is better than what you recommended,
value=badgelist if badgelist != "" else "None"

#

because "" evaluates to False and any string that is not empty evaluates to True

cold sonnet
#

I did the first one before

#

I thought it only returns False to None and empty lists and stuff like that

#

everything but empty strings

manic wing
#

it doesnt

#

!e py print(bool([]), bool(""), bool({}), bool(...), bool(False))

unkempt canyonBOT
#

@manic wing :white_check_mark: Your eval job has completed with return code 0.

False False False True False
manic wing
#

"" evalutates to False

junior verge
#

how to check your discord.py version in the terminal?

manic wing
#

discord.__version__

junior verge
#

Yeah but what do I type

manic wing
#

!e py import os print(os.__version__)

unkempt canyonBOT
#

@manic wing :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | AttributeError: module 'os' has no attribute '__version__'
manic wing
#

thats what it would be

#

builtin modules dont have versions

junior verge
#

yeah it works

manic wing
#

!e globals().getitem("print").call(dir(import('os')))

junior verge
#
import os
import discord
print(discord.__version__)
``` just did that xD
unkempt canyonBOT
#

@manic wing :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | KeyError: 'print'
junior verge
#

u good

manic wing
#

!e builtins

unkempt canyonBOT
#

@manic wing :warning: Your eval job has completed with return code 0.

[No output]
slate swan
#

Since when does this come up in pycharm? And how to remove it?

slim ibex
#

because discord.Client is bad

#

Use discord.ext.commands.Bot. It’s a subclass of Client, with commands, so there is no reason to not use it

vocal plover
#

What if I don't need commands?

slim ibex
#

???

#

that’s literally the whole point of a discord bot?

slate swan
vocal plover
#

Metric collection, for example

slim ibex
#

yes, but most people won’t be doing that

#

And you should still use commands.Bot regardless

vocal plover
#

sometimes there is a reason

slim ibex
#

there is zero reason to not use commands.Bot

slate swan
#

is there any way to change all @client.command to @bot.command in a short amount of time?

vocal plover
#

It's more complex and a bit heavier on performance because it does command processing too, if you don't need that why use it

slim ibex
#

find all the @client and replace with @bot

#

You will also have to change your variable name that instantiates the bot

slate swan
#

is there a shortcut to edit all in the same time? like in visual studio code?

slim ibex
slim ibex
#

just hover over them and read what it says

tidal hawk
#

Which basically does the same like CTRL + H in Vscode

#

But it also refactors all of the variables from different files, which is nice

slate swan
#

yea got it the message is gone now thanks!

slate swan
cloud dawn
tidal hawk
#

Refactor all*

slate swan
cloud dawn
slate swan
# slate swan its Client?

well i changed all Client to bot and now this is happening ive tried to rename it to client again but did nothing

slate swan
spring cape
#

Hello guys, I'm using nextcord to make a bot for a discord server and currently developing a ticket system. I'm stuck on making the basic logic, closing the ticket, opening and deleting.
The main problem is making a close, delete and open commands and making those commands restricted to the staff.
I've tried a lot of things but nothing seems to work properly.
Does anyone have a working ticket system and is willing to guide me in the right direction on how I should approach this problem?

slate swan
tidal hawk
cloud dawn
tidal hawk
#

I was wondering before, is there a similar thing in Vscode?

#

Which also refactors the imports, file names etc

#

Extension of some kind perhaps

cloud dawn
royal jasper
#

i want to add a role to a user when he mention a role (using client.wait_for) how can i do it?

cloud dawn
#

Pycharm has it build in, it is open source so you could do it in theory.

tidal hawk
#

Hm okay

cloud dawn
tidal hawk
#

How would that work? Bot reads all messages and if it gets "@babaooey" then it gives him the role?

cloud dawn
#

Since you can't mention unmentionable roles.

tidal hawk
#

mhm

cloud dawn
#

Thus reaction bots were invented.

tidal hawk
#

What's the easiest way to create the python compiler into discord bot

#

!e print('hw')

#

I could use google but ur expert in this field

livid jacinth
#

How i can create an command which i can execute in the bot dm

#

?

tidal hawk
#

You can use commands in bot dm? unless you have disabled it

livid jacinth
#

No i want a command in the bot dm

slate swan
slate swan
slate swan
cloud dawn
slate swan
cloud dawn
#

!d exec

unkempt canyonBOT
#

exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
slate swan
livid jacinth
#

How i can create an command which i can execute in the bot dm?

tidal hawk
livid jacinth
#

Yes

cloud dawn
tidal hawk
#

if ctx.guild is None

livid jacinth
#

ahh thx

cloud dawn
unkempt canyonBOT
#

@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

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

New in version 1.1.
cloud dawn
pliant gulch
cloud dawn
#

Because egnlish

pliant gulch
#

For a second there I thought you meant like saving state, saving variables etc

#

Save & Safe are two different words 👁️ 👁️

livid jacinth
#

How i can get the message after execute the command?

cloud dawn
#

Message of whom? The bot send or you send.

livid jacinth
#

No i mean you execute the command and if you send then message the will be deleted by the bot

cloud dawn
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
cloud dawn
#

Has a delete_after kwarg you can use accepts int & floats is in seconds.

livid jacinth
#

Okay thank you

solar summit
flat solstice
#

true

cloud dawn
#

@flat solstice Why would you need this?

flat solstice
# cloud dawn <@!365262543872327681> Why would you need this?

in case i need to retrieve data that the bot stores that isn't normally exposed by a command, mostly for responses that don't need a guild ID. it's useful is situations where I can't access the db host but need data from the db, perhaps for troubleshooting purposes

rocky hornet
#

what do you think of ```py
class MyBot(commands.Bot):
async def login(self, token):
await super().login(token)
self.name = (await self.application_info()).name

rocky hornet
#

im asking about the idea

#

does it seems like a not terrible idea

slate swan
#

well im not sure what it does but it looks fine to me

rocky hornet
#

saves app name inside bot's object so the bot is always aware of its name

#

can use that in responses

slate swan
#

doesnt a bot object already know its name?

rocky hornet
#

it knows its user name but not app name

#

and bot object isnt always accessible

pliant gulch
#

Where does the API require the application name again

#

I forgot, but probably somewhere right

rocky hornet
#

require?

slate swan
#

why would it require the apps name?

rocky hornet
#

it requires a token to log you in

slate swan
#

ofc

pliant gulch
rocky hornet
#

none?

#

i intend to use that for user reponses

cloud dawn
#

And why do you need it at the start of a session?

pliant gulch
#

User responses?

#

Wouldn't it make sense to store the full app info object to your bot, rather than just the name as well??

rocky hornet
#

like u do !help and u say f"{bot.name}'s help:"

pliant gulch
#

That's a waste of a call if you only use it for the name

#

It would make more sense to store something like bot.info

rocky hornet
slate swan
#

i dont really see any reason why this would be necessary

rocky hornet
#

bot's user name may change e.g. on some events like new year or other occasions

pliant gulch
#

Application is niche anyways, just give the full data from the first request to not require any further ones

rocky hornet
#

i dont see a problem with that

pliant gulch
#

I don't want to make a full batch of cookie dough and only bake one cookie

slate swan
#

and what happens if the app name is different to the bots namerooThink

pliant gulch
#

Same principle

rocky hornet
#

api calls dont matter before connect() occurs

pliant gulch
#

An API call is an API call? You still have ratelimits and you also use up bandwith

rocky hornet
#

i want it to be consistent

slate swan
pliant gulch
rocky hornet
#

discord.Client.connect if we're talking dpy

rocky hornet
rocky hornet
#

mobile data will give u a random IP tho

pliant gulch
#

I'm totally confused here, application name would be the one the developer seens on the frontend, not the bot's account username. In the example you shown it would be weird in cases where Application Name is Foo and the actual bot's user account name is Bar

rocky hornet
cloud dawn
#

I'd use my vps.

rocky hornet
#

but you still want the original Bot to appear in all bot's messages

#

you can use heroku or railway

slim ibex
loud junco
#

how do i create a var in another file and call it in main.py

rocky hornet
slim ibex
rocky hornet
#

cuz u heard it from somewhere?

cloud dawn
rocky hornet
#

oh guess what a discord bot is a web service

cloud dawn
slate swan
slim ibex
#

what are you grtting at here?

cloud dawn
rocky hornet
#

who cares about what its meant for? heroku is a solid platform if you're looking for a free solution to host your bot

cloud dawn
#

But @slim ibexit was for a temporary power outage to launch his bot not meant as permanent solution.

rocky hornet
#

it gets the job done and is not too bad at it

cloud dawn
slate swan
#

heroku isnt really ment for botsrooThink

rocky hornet
rocky hornet
loud junco
rocky hornet
#

these people are just ignorant, yes its more than fine

slate swan
#

why would the gateway not notice an api call?

cloud dawn
cloud dawn
slate swan
rocky hornet
#

your best argument is "its not meant for that"

#

💀

loud junco
rocky hornet
#

when its literally free

slim ibex
#

from personal experience, it is so annoying that Heroku will spin up a URL which can get messy. It also restarts a lot. In addition, there isn't the best CPU and RAM in Heroku, so a big bot would go on fire.

stone beacon
#

🗿

loud junco
#

from item import item

cloud dawn
loud junco
#

wait wait
i accidentally delete whole chunks :/

rocky hornet
slate swan
pliant gulch
#

And again, to go on the fact it's shared, that means your resources are shared as well

cloud dawn
slate swan
#

ive never seen andy lose an argument😔

rocky hornet
#

my voice always worked on heroku, bot doesnt restart ¯_(ツ)_/¯

rocky hornet
#

for what it offers, its good

slate swan
#

for hosting bots*

slate swan
loud junco
#

@cloud dawn
this is item.py

from replit import db
async def item(ctx):
  global userid, cooked_pogchop, beef, steak, wool, map_scrap
  userid = int(ctx.author.id)
  cooked_pogchop =  db[userid + 'cooked_pogchop']
  beef =  db[userid + 'beef']
  steak =  db[userid + 'steak']
  wool =  db[userid + 'wool']
  map_scrap =  db[userid + 'map_scrap']
rocky hornet
loud junco
slate swan
loud junco
slim ibex
rocky hornet
cloud dawn
slate swan
loud junco
rocky hornet
loud junco
#

so...

cloud dawn
slate swan
pliant gulch
loud junco
slim ibex
#

what he is doing should work. he just needs to open and parse the json file. But, JSON is not a suitable DB. In addition, the replit DB is a key value db

pliant gulch
rocky hornet
#

slow, limited, inefficient

pliant gulch
cloud dawn
rocky hornet
#

i just want to set up my bot and not manage it

loud junco
slim ibex
#

ik

loud junco
#

so what i do :/

slim ibex
#

regardless, @loud junco, don't use replit's db or any db that is JSON (key value stores are FINE though such as Redis, and MongoDB)

rocky hornet
#

objectbase 😌

cloud dawn
#

mongo joined the chat

slate swan
#

mongo in a sense

class Mongo(json):
    ...
```🗿
slate swan
#

big stroke

cloud dawn
loud junco
#

i just saw something

#

this is wrong right?

slim ibex
#
  1. __init__ should not be async or take ctx
  2. class Stats not class stats()
slate swan
#

more like a big dict

pliant gulch
slate swan
pliant gulch
#

No

slate swan
cloud dawn
loud junco
slim ibex
pliant gulch
slim ibex
#

bro def just wrote that rn

slim ibex
#

oh shit I go into the Rust server and see this long ass codeblock

slate swan
slim ibex
slate swan
#

😳

cloud dawn
slate swan
cloud dawn
#

We went from repl.it db to mock mongo db to females, oh the circle of life.

slate swan
loud junco
#
class item():
  def __init__(self, ctx):
    self.userid = int(ctx.author.id)
    self.cooked_pogchop =  db[self.userid + 'cooked_pogchop']
boreal ravine
loud junco
#

so how i fix that

boreal ravine
#

don't use it

loud junco
#

:/

#

bruh

boreal ravine
loud junco
#
class stats:
  def __init__(self, ctx):
    self.userid = str(ctx.author.id)
    self.helmet = db[self.userid  +'helmet']
```if this is the variable how do i call it
stats.helmet?
loud junco
#

eh
why obj
why not stats

boreal ravine
#

just get it by ```py
_stats = stats(ctx)
_stats.helmet

cloud dawn
unkempt canyonBOT
#

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

Dave
loud junco
#

:/

#

so i say it as obj.helmet in main.py?

cloud dawn
slate swan
#

what would happen if you make a class initiate a coroutine?

loud junco
#

ERROR

boreal ravine
loud junco
cloud dawn
unkempt canyonBOT
#

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

diamond
loud junco
cloud dawn
boreal ravine
boreal ravine
cloud dawn
slate swan
pliant gulch
#

You could do a class method, or alternatively run a task in the constructor

slate swan
#

nothing i just wanted to know what error it would raise lol

slate swan
#

lol

left crater
#

how can i get a watching status?

slate swan
left crater
#

easy is not an answer

boreal ravine
unkempt canyonBOT
slate swan
#

no

slate swan
#

do it in the constructor

#

Because I make an event

#

and cycle through multiple

left crater
#
Traceback (most recent call last):
  File "C:\Users\nikit\PycharmProjects\huhh\docs\main.py", line 26, in <module>
    bot = commands.Bot(command_prefix='%', help_command=None, intents=intents,
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\bot.py", line 158, in __init__
    super().__init__(**options)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\ext\commands\core.py", line 1156, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\client.py", line 235, in __init__
    self._connection: ConnectionState = self._get_state(**options)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\client.py", line 265, in _get_state
    return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
  File "C:\Users\nikit\PycharmProjects\huhh\discord\state.py", line 205, in __init__
    raise TypeError('activity parameter must derive from BaseActivity.')
TypeError: activity parameter must derive from BaseActivity.``````py
bot = commands.Bot(command_prefix='%', help_command=None, intents=intents,
                   status=discord.Status.online, activity=discord.ActivityType.watching, case_insensitive=True)```
slate swan
#

!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
#
await client.change_presence(activity = discord.Activity (type = discord.ActivityType.watching, name = f"{len(client.guilds)} servers  {len(set(client.get_all_members()))} Members| .help for commands"))

@slate swan I did mine like that

left crater
#

if you did it in on_ready thats a big nono

slate swan
left crater
#

how would i do it in a bot contructor?

slate swan
#

you did?

slate swan
#

just add another comma

#

wut

#

ok I'm confusing myself now

#

🤣

slate swan
boreal ravine
left crater
#

yeah i figured it out

slate swan
#

name = "your message"

#

how I did mine idk

left crater
#
                   status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name="some bitches"), case_insensitive=True)```i did this
slate swan
#

@left crater btw there are other methods as well. such as

discord.ActivityType.playing
discord.ActivityType.listening

left crater
#

also streaming

slate swan
#

!d discord.ActivityType.streaming

unkempt canyonBOT
peak badge
#
import discord
from discord.ext import commands, tasks

bot = commands.Bot("!!")



@bot.event
async def on_ready():
  print(f"Olá, estou online como {bot.user}.")

@bot.event
async def on_message(message):
if message.author == bot.user:
  return

if "palavrão" in message.content:
  await message.channel.send(
    f"Por favor, {message.author.name}, não ofenda os demais membros!"
  )

await message.delete()

await bot.process_commands(message)

@bot.command(name="oi")
async def send_hello(ctx):
name = "Olá, " + name 

await ctx.send(responce)

@tasks.loop(seconds=10)
async def current_time():
  now = datetime.datetime.now()

now = now.strftime("%d/%m%Y às %H:/%M:/%S")

channel = bot.get_channel(951475916679311460)

await channel.send("Data atual:" + now)

bot.run(os.environ['TOKEN'])
#

why does it give error?

cloud dawn
#

!indention

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

peak badge
#

serves wrong '-'

stark lintel
#

fsa f

#

oops

peak badge
#

did not work :/

slate swan
#

Variable naming, it's a Bot class, so name it bot, not client,
import order, libraries like os should be imported before other packages ( pep8) ```py
import os

from nextcord.ext import commands

#

Everything else looks fine

#

Oh nvm

#
[bot.load_extension(f'cogs.{fn[: -3]}') for fn in os.listdir("./cogs") if fn.endswith(".py")]

you can use list comps

#

it would return a list of cogs as well which can come in handy

#

And in the end you can have a comment #okimii is cool
To make your code look cooler

slate swan
slate swan
slate swan
#

no one calls me thatAG_CryCat

slate swan
#

good point

slate swan
pliant gulch
slate swan
#

and that one liner wont handle errors

slate swan
#

😔 plus, __init__.py users like me will hate u

#

less than 10 cogs would be fineisFine

boreal ravine
cloud dawn
slate swan
boreal ravine
cloud dawn
unkempt canyonBOT
pliant gulch
#

Cogs are classes, so namespace file would be helpful when needing to use them in other areas

boreal ravine
#

A repository

#

awesome

slate swan
#

yeah its good to have good namespaces

boreal ravine
#

yes

slate swan
#

unlike discord.member.MemberrooFine

pliant gulch
#

In one of my projects the namespace was polluted because of an un-proper __all__, so I just had a random aiohttp in my namespace

slate swan
#

💀

slate swan
#

wouldnt that sorta balance it in speed

slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

<map object at 0x7f686a5e1600>
slate swan
#

!e print(list(map(str, [a for a in range(101)])))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']
cloud dawn
#

!e ```py
print(map(str, range(101)))

unkempt canyonBOT
#

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

<map object at 0x7fb30c4a9150>
cloud dawn
#

!e ```py
print(list(map(str, range(101))))

slate swan
#

i forgot range returns a listisFine

unkempt canyonBOT
#

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

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']
slate swan
#

thats not my point thogopher

dull terrace
#

can someone name the most common games that bots have

#

one is general gambling like blackjack

slate swan
#

look into dank member & owo, you'll get pretty much many ideas

cloud dawn
dull terrace
#

played owo a bit but drawing a blank

slate swan
slate swan
#

( the code is same in dpy so dont shout that its disnake)

#

it should

brisk zodiac
#
import discord
from discord.ext import commands
import os
from keep_alive import keep_alive

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

@client.event
async def on_ready():
    print("Logged in")

@client.event
async def on_member_join(member):
    try:
        channel=client.get_channel(955795195268567130)
        try:
            embed = discord.Embed(colour=discord.Colour.green())
            embed.set_author(name=member.name, icon_url=member.avatar_url)
            embed.add_field(name="Welcome" ,value=f"**Hey,{member.mention}! Welcome to {member.guild.name}\nI hope you enjoy your stay here!\nThanks for joining**", inline=False)
            embed.set_thumbnail(url=member.guild.icon_url)
            await channel.send(embed=embed)
        except Exception as e:
            raise e
    except Exception as e:
        raise e

keep_alive()
client.run(os.getenv('BOT_TOKEN'))```
#

This code worked but when someone joined my sv it didn't say anything

slate swan
#

!intents

#

wait you got the intents,

slate swan
#

but you didnt add it in your client

#

man, did you mixed this code from multiple sources

#

sarthak is tired of mixed bad yt tutorialsAG_WorrySadge

dull terrace
#

my whole code is a bad youtube tutorial

slate swan
#

true, especially the client ones

slate swan
slate swan
#

or when they subclass Client😔

dull terrace
slate swan
#

💀 it seems like discord.py is the only library which takes token as an argument in run/start
all other libraries i tried ( hikari, rin, hata) have it inside their Client/GatewayBot itself

pliant gulch
final iron
slate swan
pliant gulch
#

You don’t always need to make it a list, it’s a generator

#

You could use next, you could unpack it etc

#

You can iterate it and so on

slate swan
#

good point

slate swan
#

?

pliant gulch
#

Generators are interators

#

Or iterable

slate swan
#

ah ic

pliant gulch
#

Which saves compute time when dealing with large data sets

slate swan
slate swan
final iron
sullen pewter
#

I've just got an order and this is what he said:
"Can the bot connect with my bot?
I mean, I code my bot in bdfd and you code bot in discord.py
Do they can be connect each other?
For example. When I run /wallet
Then my bot will give me info that how much coins that I have.

Then when I run /buyTV
Then your bot will deduct my coins

Is it possible?"

#

Is it possible?

solar summit
#

wdym bot connect with my bot

sullen pewter
#

Money is in one bot

#

Shop in another

sullen pewter
final iron
#

If you both use the same database file or whatever it's called then they can be "linked"

sullen pewter
#

Ok

solar summit
#

a shared database where they can both access it, just put it in the same directory

sick birch
#

You can have a central API for both bots to access

#

The API would act as a middleman between your database and both of your bots

solar summit
#

i mean seems a bit complex for something like that, depends on how much data his gonna be dealing with

sick birch
#

If the API is hosted locally on the same machine as the bots network latency is going to be negligible

solar summit
#

thats fair, could also be expanded onto other things

sick birch
#

Yeah I like to practice seperation of concern so the discord bot is only really a front-end thing

#

All it does is get data, send data to an API, and display the data in a nice form

#

All the heavy lifting and logic is done by an API server

solar summit
#

never thought of it that way

#

now i cant unsee discord bots as a front end thing 😂

sick birch
#

Haha, glad I could provide a new perspective

#

Also one advantage of the method I mentioned is you don't need extra dependencies like motor as aiosqlite or any python async connectors really. You just need aiohttp and you can make HTTP requests to your localhost

#

& the backend can be whatever language you want really. Go with javascript for convenience or if you want speed you can write it in C or Rust (not sure if those support webservers)

glacial echo
#

if i have a dict of channel id, where the value stored for each channel is a list of user id, how would i check position 0 of the current channel

brave flint
#

how to get command int?

#

total command int

slate swan
brave flint
#

nvm and i mean len

slate swan
#

you mean the len of all commands? im not sure how you would get the len of a command

glacial echo
#

how do i run a delete message ?

#

await ctx.message.delete() doesnt work

#

waiitttt

#

slash commands do that automatically

boreal ravine
#

No

#

slash commands don't have messages

glacial echo
#

right

#

w h y

vale wing
slate swan
vale wing
#

Or do the ephemeral

maiden fable
#

Yes

glacial echo
#

i mean

#

the idea was other players dont see the message, so it being a slash command solved that problem

#

but rn its not letting me run commands

#

it worked once though

boreal ravine
#

how does a message become "done"

glacial echo
slate swan
slate swan
glacial echo
#

this is slash commands

slate swan
#

ctx for slashes 😔

boreal ravine
glacial echo
#

but idk what part of that is missing

boreal ravine
glacial echo
#

see above

slate swan
#

why not just use main?

glacial echo
#

from what i could find discord.py doesnt have slash commands documented anywhere

slate swan
#

check repo

boreal ravine
#

they implemented slash commands a while ago

slate swan
glacial echo
#

that looks like itd need me to do a total rewrite, whereas this so far has been a refactor

boreal ravine
#

yes

slate swan
#

lovely thing about dpy you need to make a whole rewrite because of all the new breaking changes

glacial echo
#

ok but so far this has now worked

#

using that other library

boreal ravine
# glacial echo

make an issue on the github and wait for a response i guess or ask in the support server if they have one

glacial echo
#

and it was just a refactor

#

do slash commands not have channels?

boreal ravine
#

they do

boreal ravine
slate swan
unkempt canyonBOT
slate swan
#

they do have channels

boreal ravine
slate swan
slate swan
glacial echo
#

do slash commands not have "authors" then?

maiden fable
#

Ofc

boreal ravine
slate swan
#

!d discord.Interaction.user

unkempt canyonBOT
maiden fable
#

They have channel, author and message

slate swan
slate swan
maiden fable
slate swan
slate swan
slate swan
#

I'll get some sleep 😔 bye

maiden fable
#

Not surprising lemon_pensive

slate swan
maiden fable
#

Lmao

slate swan
#

ok

slate swan
glacial echo
boreal ravine
maiden fable
slate swan
maiden fable
#

Then did u just want me to waste my energy and write that? lemon_pensive

glacial echo
maiden fable
#

Also ctx.channel_id

#

!d discord.Interaction.channel

unkempt canyonBOT
maiden fable
#

This is also there tho

slate swan
boreal ravine
maiden fable
#

Means the same thing as wasting my energy to save yours. Understandable lemon_angrysad

slate swan
#

!ot

unkempt canyonBOT
maiden fable
slate swan
#

take the conversation somewhere else

maiden fable
glacial echo
slate swan
#

youre trying to index a dictionary with an object that isnt a key

maiden fable
# glacial echo wha

There's a high probability that the channel ID in the dict is a string but interaction.channel_id returns an int

glacial echo
slate swan
#

!e print({1: 2}[3])

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | KeyError: 3
maiden fable
boreal ravine
glacial echo
slate swan
#

not sure why they both said that

maiden fable
#

Nvm I'm most probably outta my mind

glacial echo
#

ok so the issue is? that the check fails because the key isnt in the dictionary?

glacial echo
#

but then shoudlnt that not break?

slate swan
#

define break

glacial echo
#

shouldnt the check return false and move on to the else

#

or is it more fundamental than that

slate swan
#

its raising a keyerror

#

you would need to catch the error

glacial echo
#

how do i check if a variable is in the keys of a dict

#

i think whats going fucky is me trying to implement per-channel games

boreal ravine
#
if client.players.get(ctx.channel_id, None) is None:
    return
``` this'll handle the keyerror for you
glacial echo
#

as before only the game active in a channel was per channel

slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

yup
slate swan
glacial echo
#

it errored but still sent the mesage

#

oh do i need to like

#

.append()

maiden fable
#

No

#

!d dict.update

unkempt canyonBOT
#

update([other])```
Update the dictionary with the key/value pairs from *other*, overwriting existing keys. Return `None`.

[`update()`](https://docs.python.org/3/library/stdtypes.html#dict.update "dict.update") accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: `d.update(red=1, blue=2)`.
boreal ravine
boreal ravine
glacial echo
boreal ravine
#

add that to your code

glacial echo
#

ok but

#

if the channel isnt a key it needs to become a key

boreal ravine
glacial echo
#
async def joinGame(ctx: interactions.CommandContext):
  #await ctx.message.delete()
  if ctx.channel_id in client.players == False:
    client.players[ctx.channel_id] = []
  if ctx.author.id in client.players[ctx.channel_id]:
    await ctx.send(f'{ctx.author}, you are already in the game, no need to join twice.')
  else:
    await ctx.send(f'<@{ctx.author.id}> has joined the round!')
    client.players[ctx.channel_id].append(ctx.author.id)
    print(client.players[ctx.channel_id])
slate swan
#

!e

if 1 in {1: False} == False:  print("Yep")
unkempt canyonBOT
#

@slate swan :warning: Your eval job has completed with return code 0.

[No output]
glacial echo
unkempt canyonBOT
#

@glacial echo :warning: Your eval job has completed with return code 0.

[No output]
glacial echo
#

hmm

#

idk

maiden fable
#

U need True

glacial echo
#

slight issue

maiden fable
#

Hm?

glacial echo
#

whatever datatype its getting, it sure as hell isnt a unique user id that is getting stored away anywhere

maiden fable
#

Show code

glacial echo
#
async def joinGame(ctx: interactions.CommandContext):
  #await ctx.message.delete()
  if ctx.channel_id not in client.players:
    client.players[ctx.channel_id] = []
  if ctx.author.id in client.players[ctx.channel_id]:
    await ctx.send(f'{ctx.author}, you are already in the game, no need to join twice.')
  else:
    await ctx.send(f'<@{ctx.author.id}> has joined the round!')
    client.players[ctx.channel_id].append(ctx.author.id)
    print(client.players)
slate swan
maiden fable
glacial echo
# glacial echo

here i ran /join_game twice in a row as the same user in the same channel

maiden fable
#

Ah

glacial echo
#

it has created a new "channel" key

maiden fable
#

Can u print the dict?

#

client.players

glacial echo
#

thats uh

#

literally what the output is

#

those arent errors in teh ss

maiden fable
#

What the fuck

#

Which module u using?

maiden fable
#

That's why lemon_pensive

#

Stop using that lib and instead either use dpy master version or a fork like nextcord, disnake

slate swan
#

use main!

glacial echo
#

god dammit

#

so i have to rewrite?

maiden fable
#

Some part, yup

slate swan
#

or disnake which you dont really need to do a rewrite

maiden fable
#

The module u r using rn has fucked up big time

glacial echo
#

and also the dpy main thing doesnt have any documentation that i can understand for slash commands

#

sorry, "interactions"

glacial echo
#

it has documentation

slate swan
maiden fable
glacial echo
#

I cant understand it

maiden fable
#

Oh haha

#

Well then u should look into using a fork, like oki suggested

slate swan
unkempt canyonBOT
glacial echo
#

yay time to install a third discord api

slate swan
glacial echo
#

but

#

i just installed disnake using the pip command they have on the installation page on the docs

slate swan
#

restart your editor

glacial echo
#

true i can do that easy

#

i really liked how simple that was

#

and now i might have to rewrite huge chunks of this to make stuff work

#

comign back to bot dev after a year or two of not touchign teh discord API has been roadblock after roadblock

slate swan
maiden fable
#

How tf did it work before tho

glacial echo
#

client = disnake.Client(case_insensitive = True)

#

ive been using this the whole time

maiden fable
#

U need commands.Bot

glacial echo
#

client = client whatever the fuck

maiden fable
#

How tf did that even work

slate swan
#

...

glacial echo
#

but also it looks like i need to totally rewrite to use slash commands

maiden fable
#

Okay it's time for me to stop believing in reality anymore

glacial echo
#

ill deal with it and just rewrite i suppose

#

ugh im stressed and its making me bite my nails again

#

this whole relearning everythign API realted hurts

maiden fable
#

Do one thing

sick birch
maiden fable
#

Change the disnake.Client to commands.Bot after importing commands from disnake.ext

slate swan
# glacial echo client = client whatever the fuck
import disnake
from disnake.ext import commands

bot = commands.Bot(command_prefix="your_desired_bot_prefix", intents=disnake.Intents.default())

@bot.slash_command(name="uwu", description="will totally uwu you")
async def uwuer(inter: disnake.Interaction):
  return await inter.response.send_message("uwu")

@bot.event
async def on_ready():
  print("uwu")
bot.run("your bot token")```
#

is a small example

maiden fable
#

is a small uwu example

slate swan
#

yes that

slate swan
#

intents expected Intents class from disnake but got given a discord class

maiden fable
#

Hmm

slate swan
#

whatever uh

maiden fable
#

Wait

slate swan
#

would probably raise something like intents must derive from Intents

slate swan
slate swan
#

it does

maiden fable
slate swan
slate swan
#

disnake's Bot and discord's Intents

#

weird my subclass doesnt raise that error maybe the error gets eaten or it gets set to None

glacial echo
#

mmmmmmm

unkempt canyonBOT
#

disnake/state.py lines 228 to 232

if intents is not None:
    if not isinstance(intents, Intents):
        raise TypeError(f"intents parameter must be Intent not {type(intents)!r}")
else:
    intents = Intents.default()```
maiden fable
#

It does check

slate swan
glacial echo
#

my slash commands dont exist after setting test_guilds=[my_guild]

maiden fable
slate swan
maiden fable
slate swan
#

test_guilds is in the bot constructor

maiden fable
# slate swan why

Sadly idfk, would have been better if Danny allowed inputting the binary operators manually but well 🤷‍♂️

maiden fable
#

Stop with your whys

slate swan
glacial echo
#

my bot no worky

#

no slash commands exist

slate swan
#

and the decorators are all wrong

#

you need to do client.slash_command

boreal ravine
boreal ravine
#

did you guys know that discord.py was previously called pydiscord?

glacial echo
#

the fuck

#

but i GAVE you an argument

#

the only valid argument that does anything in fact

#

do i have to specify the allowed values?

#

do slash commadns not take dynamic values?

#
@client.slash_command(
  name="start_game",
  description="Start a game from the list."
)
async def startGame(ctx, gameID):
  client.channelGame[ctx.channel.id] = gameID
  print(client.channelGame)
  embedVar = discord.Embed(title=f"The game has begun!", description="", color=0x00ff00)
  embedVar.add_field(name="Score to Beat:", value=client.leadWord + " worth " + str(client.leadWordPoints) + " points from " + str(client.leadPlayer), inline=False)
  embedVar.add_field(name="Next Player: ", value=f"<@{client.players[ctx.channel.id][0]}>", inline=False)
  client.currentEmbed = await ctx.send(embed=embedVar)
  client.currentGameChannel = ctx.channel.id
maiden fable
slate swan
#

dpys source isnt that advance you just need to dig into the 5 parent classes of each subclass

glacial echo
#

this is being fucky

slate swan
#

nice

boreal ravine
glacial echo
glacial echo
#

annnyyways

#

thats an overcomplicated command that doesnt really need a param rn as i have a single game

glacial echo
#

annnnyways part 2: electric booglaoo

the mebed is sent but then cant be edited?

#

fancy

#

thanks for that

slate swan
slate swan
glacial echo
#

off-topic but relevant

#

as im working with slash commands and that makes slash commadns lok better

glacial echo
#

and makes it visually behave as expected

glacial echo
slate swan
#

thats like saying how to make a carrot an apple

#

i dont know i havent seen your code

glacial echo
inner epoch
#

Is it possible increase font size of footer of embed?

slate swan
#

can you?

boreal ravine
#

No

inner epoch
boreal ravine
#

it doesn't support flavored markfown

#

only normal text/emojis

slate swan
#

smh

inner epoch
#

What I want exactly is a title of embed then a image and then some text

boreal ravine
inner epoch
#

If I try adding field it gets added above the image so I thought to go with footer

glacial echo
#

is the text dynamic

inner epoch
glacial echo
#

make it part of the image

inner epoch
glacial echo
#

dynamic image generation

inner epoch
#

Yea....I can do that!!PIL

glacial echo
#

ugh making the embed and user lists channel specific has caused issues

#

i now have to make all client variables channel tracking dictionaries or the points system breaks again

#

welp im callign it a night

inner epoch
#

Aha night man!!Have a good one

glacial echo
#

gonna update my trello and shut down

boreal ravine
#

What shoupd I call my yggdrasil copy?

maiden fable
maiden fable
slate swan
boreal ravine
slate swan
#

like literally what i said btw

boreal ravine
#

thanks okimii

lone torrent
#

#include <iostream.h>

glacial echo
#

this is step by step

#

i just have ADHD so i am very scatterbrained

#

and also originally i didnt realise id need to make every client variable a channel tracking dict, but thats trivial at this point

slate swan
maiden fable
maiden fable
glacial echo
#

its not too frustrating now that i got everythign smoothed over as now its a few minor bumps and not just a fuckign cliff

glacial echo
slate swan
maiden fable
#

Just had a rough picture of what I need, in my mind that's it

glacial echo
#

the trello is to keep myself organized and allow my teacher to see my progress

slate swan
#

nvm

maiden fable
glacial echo
#

also making a new card directly in the completed tab to make myself fee laccomplished becasue i solved a problem that came up

maiden fable
#

Cool

maiden fable
#

Can't argue with that

slate swan
glacial echo
#

gott asay

#

disnake dev is pog, they actually wrote documentation and logical methods for writing slash commands

maiden fable
#

Hahaha

glacial echo
#

this was so painless once i figured out how to not be stupi

maiden fable
#

Cool

glacial echo
#

ohhh this is nice