#discord-bots
1 messages · Page 924 of 1
It's the new way to start dpy bots based on dpys new asyncio changes
!d discord.TextChannel.history
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...
thanks
sadly when i was 13 i was busy with games lmao
🥲😗🥺
I still am
lol
I'm not any proud
rainbow
Don't get me started
Try game deving, you will see how fun it is
it is

yes
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))
that means you need to upgrade your dpy
When I run this command it sends 4 things but i only want it to send 1
also setup() and add_cog have been changed to be asynchronous in the latest updates to dpy
How do I fix it
you mean unindent?
I'm gonna search up your messages and correct every single grammar mistake you've ever made on this server
nah jk
I'm gonna search up your messages and correct every single grammar mistake you've ever made on this server.*
🗿
jkn't
wouldn't
You talking to me?
yes
Oh
Don't stop
nah Imma stop
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
I need to keep it indented
!d discord.Member.public_flags
property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.public_flags "discord.User.public_flags")
check if this is empty or not
then it won't do what you want it to
But I will get a error
just remove four spaces from the send line 😦
Ok
if member.public_flags:
#he has badges
else:
#he don't have badges
doesn't
okay thanks
just slang
It still sends 4 messages
show what you did
you removed like 8 spaces
No I removed 4
you're indenting with 2 spaces?
Okimii*
are u single too
No that’s 0
nah @final iron is my gf
oh
😳
anyways, you unindented your send by two indents

Ok
it has to be on the same level as your for loop
😳
😏
Thanks
two dents*
In embeds.0.fields.0.value: This field is required I'm still getting this error.
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
value=badgelist, is it because of this?
what should i add into it then?
value=badgelist if badgelist else "None"
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
i dont get what you mean by list
value=badgelist if badgelist != "" else "None"
the value is badgelist if badgelist isn't empty
else the value is None
do i still need if user.public_flags:
got an idea use a list right, since the user cannot have more than 1 hypersquad tag and then get the "emoji" from the list e.g value=badgelist[0] if badgelist != "" else "None"
don't think there's a need to do that
still doesnt work
i mean why u need to use a list since the user cannot have more than 1 hypersquad tag
he don't use a list
oh my bad i saw "badgelist" thought it was a list
in the badges field it just returns with :
!e py empty = "" if 1 == 1: empty += "2" print(empty) print(empty)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | 2
!e
empty = ""
for i in range(10):
if i < 8:
empty += str(i) + "\n"
print(empty)
@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
there could be many stuff in public_flags
like?
ill just leave it outta my code
too hard
so basically that for discord badges ?
public_flags is a list of badges
i just want the hypesquad
it doesnt
firstly i dont even know what should be in my code, you said about a list then said no, and im confused now
there are always multiple ways to do something
but i dont know what ways, thats why im asking
you could make a list but then you'd have to join the elements
but i dont know how to, that why im asking
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?
Just verified bots
👌 thx for the answer
!e print(bool(""))
@manic wing :white_check_mark: Your eval job has completed with return code 0.
False
comprehend
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
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 :white_check_mark: Your eval job has completed with return code 0.
False False False True False
"" evalutates to False
how to check your discord.py version in the terminal?
discord.__version__
Yeah but what do I type
@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__'
yeah it works
!e globals().getitem("print").call(dir(import('os')))
import os
import discord
print(discord.__version__)
``` just did that xD
@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'
god damn containerized eval
u good
yup, nice and simple
@manic wing :warning: Your eval job has completed with return code 0.
[No output]
Since when does this come up in pycharm? And how to remove it?
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
What if I don't need commands?
but ive used discord.Client this whole time and just now it says that
No, it's not, there's plenty of things you can do which are not command based
Metric collection, for example
switch over to commands.Bot
yes, but most people won’t be doing that
And you should still use commands.Bot regardless
sure but "no reason" is a little misleading
sometimes there is a reason
there is zero reason to not use commands.Bot
is there any way to change all @client.command to @bot.command in a short amount of time?
CTRL+F
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
find all the @client and replace with @bot
You will also have to change your variable name that instantiates the bot
is there a shortcut to edit all in the same time? like in visual studio code?
Better organization with cogs, regardless if you don’t use commands or not
I think it’s like the second to last one on PyCharm that is the one that selects all occurrences of it
just hover over them and read what it says
If I remember correctly, there's an option called "refactor"
Which basically does the same like CTRL + H in Vscode
But it also refactors all of the variables from different files, which is nice
yea got it the message is gone now thanks!
well now this has come up, before it, it worked
Refractor != replace all
Refactor all*
its Client?
Still not since refractor is a algorithm that also looks at imports and references.
well i changed all Client to bot and now this is happening ive tried to rename it to client again but did nothing
no i mean aiohttp.ClientSession
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?
i had the .ClientSession small that was the problem so its fixxed again
Haven't gone into the depth of how refractor works, but it has done similiar job like Ctrl + H for me
oh alr
Well refactoring is awesome in pycharm since if you refractor a file name for example every import and reference inside the import will update as well saving you from renaming everything.
I was wondering before, is there a similar thing in Vscode?
Which also refactors the imports, file names etc
Extension of some kind perhaps
Most likely not since that extension would be huge.
i want to add a role to a user when he mention a role (using client.wait_for) how can i do it?
Pycharm has it build in, it is open source so you could do it in theory.
Hm okay
Every time someone would want a specific role would mention them..? I recommend doing something else, I could still help you if you want.
How would that work? Bot reads all messages and if it gets "@babaooey" then it gives him the role?
That's what the wanted yeah, in a given time of course. But it will keep mention everyone in that role.
Since you can't mention unmentionable roles.
mhm
Thus reaction bots were invented.
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
You can use commands in bot dm? unless you have disabled it
No i want a command in the bot dm
well
ctx.message?
well thanks it would work but how can i make it react to the message of the bot?
The easiest way but unsecure is exec
define the message e.g ```py
message = await ctx.send("d")
!d exec
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`.
🫂
How i can create an command which i can execute in the bot dm?
Okayy
Only from dm’s?
Yes
Problem with exec is that it needs heavy modifying to be actually save.
This is what the @unkempt canyon bot uses https://github.com/python-discord/snekbox
if ctx.guild is None
ahh thx
!d discord.ext.commands.dm_only
@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.
What does save here mean?
Save in terms of people running malicious code.
Oh, kek why not just say safe??
Because egnlish
For a second there I thought you meant like saving state, saving variables etc
Save & Safe are two different words 👁️ 👁️
How i can get the message after execute the command?
Like..?
Message of whom? The bot send or you send.
No i mean you execute the command and if you send then message the will be deleted by the bot
!d discord.abc.Messageable.send
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**.
Has a delete_after kwarg you can use accepts int & floats is in seconds.
Okay thank you
not much of a discord.py question
@flat solstice 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
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
should add annotations
well im not sure what it does but it looks fine to me
saves app name inside bot's object so the bot is always aware of its name
can use that in responses
doesnt a bot object already know its name?
Where does the API require the application name again
I forgot, but probably somewhere right
require?
why would it require the apps name?
it requires a token to log you in
ofc
Yea, like what endpoint need's the bot's application name though
And why do you need it at the start of a session?
User responses?
Wouldn't it make sense to store the full app info object to your bot, rather than just the name as well??
like u do !help and u say f"{bot.name}'s help:"
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
name, owner, nothing else seems useful
i dont really see any reason why this would be necessary
bot's user name may change e.g. on some events like new year or other occasions
Yea, but then you'd be wasting an API call
Application is niche anyways, just give the full data from the first request to not require any further ones
i dont see a problem with that
I don't want to make a full batch of cookie dough and only bake one cookie
and what happens if the app name is different to the bots name
Same principle
api calls dont matter before connect() occurs
thats the point
An API call is an API call? You still have ratelimits and you also use up bandwith
i want it to be consistent
on_connect? or
Consistent with what?
discord.Client.connect if we're talking dpy
with its actual name
.
yes
Why would it change?
mobile data will give u a random IP tho
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
for example your bot's name is Bot and you would like to change it to ❄️Bot❄️ on new year
I'd use my vps.
but you still want the original Bot to appear in all bot's messages
you can use heroku or railway
Ahh now it's more clear lol
don't host discord bot on heroku
reason?
its make for web services
cuz u heard it from somewhere?
By using import
oh guess what a discord bot is a web service
No it's meant to host web services, not bots.
doesnt that get triggered when it connects to a websocket to the gateway how would it make a request?
what are you grtting at here?
This is very false.
who cares about what its meant for? heroku is a solid platform if you're looking for a free solution to host your bot
????????
But @slim ibexit was for a temporary power outage to launch his bot not meant as permanent solution.
it gets the job done and is not too bad at it
@rocky hornet 
I disagree with this, it's a "decent" platform if you're looking for a private bot.
heroku isnt really ment for bots
if you make an api call between login and connect, i dont think its noticeable, at least for my bot it takes at least half a minute to connect
my bot has 50 servers and heroku is yet to fail me once
it probably is noticeable
attribute error
these people are just ignorant, yes its more than fine
why would the gateway not notice an api call?
Depending on the size of those servers and what kind of things you do with the bots it may vary yeah.
How are you importing it?
bro thats just dumb saying everyone here is ignorant💀
when its literally free
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.
🗿
from item import item
Code?
wait wait
i accidentally delete whole chunks :/
definitely not for big bots, i agree
best argument? read this bro #discord-bots message
Heroku shares IPs amongst it's servers, therefor if someone get's ratelimited on a cluster, so do you
And again, to go on the fact it's shared, that means your resources are shared as well
How is that not a valid argument?
ive never seen andy lose an argument😔
my voice always worked on heroku, bot doesnt restart ¯_(ツ)_/¯
doesnt seem like a valid complaint since its free
for what it offers, its good
for hosting bots*
bro how isnt that valid
@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']
well it is an argument, but the fact that it's free completely outweighs it
o no
ikr
Do you have an init file?
doesnt that give you just 1 month or something
nope :/
good things in life aren't free
been hosting my bot there for 2 years
Not too sure if importing is different on repl
how much guilds and members?
what will u do if u meet this kind of problem
50 guilds, 50k members
so...
Well if I get an import error check if the init file is good and if i typed it correctly.
im not sure if thats a good idea especially ratelimits
Ok, sure it's free, that's a plus. But none the less I'd rather use other options. It's all opinionated mostly, but opinions don't change the facts
so where do i create the init file
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
You have amazing enterprise level options such as AWS, IBM, GCP etc, all which have a trial
slow, limited, inefficient
1 year trial
Oracle, even has a perm free tier I've heard?
In the root.
i just want to set up my bot and not manage it
so its not working where it should work? 🤣
ik
so what i do :/
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)
objectbase 😌
mongo joined the chat
tell replit 🤣
mongo in a sense
class Mongo(json):
...
```🗿
big stroke
So the solution you're providing is using a paid database for his free hosting?
__init__should not be async or takectxclass Statsnotclass stats()
more like a big dict
Not really
take a joke
No
old timer
async class m(json):
...
``` he meant this
so just remove the async and change stats => Stats?
i was saying that as in if he liked the replit db, he could check out a key value store that is SOMEWHAT similar. But, I would much rather him use an RDBMS like SQLite
from __future__ import annotations
db = {}
@type.__call__
class __annotations__:
def __setitem__(self, key: str, value: str) -> None:
db[key] = value
user: 123
print(db["user"])
``` 😳 look at my db
shitttttttttttt
bro def just wrote that rn
you really said dict() 
oh shit I go into the Rust server and see this long ass codeblock
imagine how much females andy gets with this talent😔
shit lol
I'd ****
that guy is probably brandon

class item():
def __init__(self, ctx):
self.userid = int(ctx.author.id)
self.cooked_pogchop = db[self.userid + 'cooked_pogchop']
replit's database is blocking
so how i fix that
don't use it
don't await the class itself
okok
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?
obj.helmet
eh
why obj
why not stats
just get it by ```py
_stats = stats(ctx)
_stats.helmet
!e ```py
class Test:
def init(self, name: str) -> None:
self.name = name
some_obj = Test("Dave")
print(some_obj.name)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
Dave
obj can me any name
what would happen if you make a class initiate a coroutine?
ERROR
not say, you write it
...
!e ```py
class Stats:
def init(self) -> None:
self.helmet = "diamond"
stats = Stats()
print(stats.helmet)
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
diamond
i think i cant do the stats = Stats() in main.py
some class not declared thing will appear
Then i recommend making it a method instead so you don't have to define it.
Yeah because it's stats not Stats..

What about overriding the init using new to make init a coro
or even better use a classmethod
You could do a class method, or alternatively run a task in the constructor
wym
nothing i just wanted to know what error it would raise lol
try it
how can i get a watching status?
easy
easy is not an answer
!d discord.ActivityType.watching
A “Watching” activity type.
client.change_presence(activity = discord.Activity (type = discord.ActivityType.watching
no
thats how I do it
do it in the constructor
Because I make an event
and cycle through multiple
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)```
!code
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.
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
if you did it in on_ready thats a big nono
in what event on guild join?
nope
how would i do it in a bot contructor?
you did?
right here?
just add another comma
wut
ok I'm confusing myself now
🤣
you have to say add a name I think
try activity=discord.Activity(discord.ActivityType.watching) since Activity is inherited from "BaseActivity"
yeah i figured it out
status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name="some bitches"), case_insensitive=True)```i did this
yeah thatd work
@left crater btw there are other methods as well. such as
discord.ActivityType.playing
discord.ActivityType.listening
also streaming
!d discord.ActivityType.streaming
A “Streaming” activity type.
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?
!indention
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
did not work :/
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
bot.cogs be like..
😳
they dont call me a one liner wizard for nothing
no one calls me that
Why stop at just loading cogs
fun fact: pep8 gets mad at you
Map would probably be faster here, but also depends on data size
yeah😔
and that one liner wont handle errors
i know we've had a convo about this before🗿
😔 plus, __init__.py users like me will hate u
less than 10 cogs would be fine
Tru
why would you need that in a cogs folder
Because some cogs are properly structured?
why not? depends on what you are doing
Define "structured"
!source
Cogs are classes, so namespace file would be helpful when needing to use them in other areas
yeah its good to have good namespaces
yes
unlike discord.member.Member
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
💀
btw why would it matter if you need to make it a list?
wouldnt that sorta balance it in speed
What?
!e print(map(str, [a for a in range(101)]))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<map object at 0x7f686a5e1600>
also, that wont be a list of cogs, since load_extension returns None
!e print(list(map(str, [a for a in range(101)])))
@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']
!e ```py
print(map(str, range(101)))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
<map object at 0x7fb30c4a9150>
!e ```py
print(list(map(str, range(101))))
i forgot range returns a list
@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']
thats not my point tho
can someone name the most common games that bots have
one is general gambling like blackjack
it should return the cog name smh😔
look into dank member & owo, you'll get pretty much many ideas
No range returns a range object not a list.
played owo a bit but drawing a blank
right sorry but its an iterable
( the code is same in dpy so dont shout that its disnake)
it should

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
why is their 2 try except blocks that catch an error and then raises them?
but you didnt add it in your client
man, did you mixed this code from multiple sources
sarthak is tired of mixed bad yt tutorials
my whole code is a bad youtube tutorial
true, especially the client ones
or the Client ones
lemme guess, lucas?
or when they subclass Client😔

💀 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
Ok, not sure what your question is though
🗿
well you need to make it a list with the list converter so wouldn't that make it sorta slow?
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
good point
doesnt map return an iterator hence why you use next
?
Technically yes, but it’s a generator
Generators are interators
Or iterable
ah ic
That being said, since it is a generator values are generated on demand, this makes them “lazy”
Which saves compute time when dealing with large data sets

do you like search for pep8 in:#discord-bots 
No I'm just lonely so I read chat
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?
a currency bot?
wdym bot connect with my bot
Will that work?
Just share a database
If you both use the same database file or whatever it's called then they can be "linked"
Ok
a shared database where they can both access it, just put it in the same directory
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
an api just for a discord bot though? I guess mongodb could work?
i mean seems a bit complex for something like that, depends on how much data his gonna be dealing with
Nothing wrong with it. I do it for my bots. I write the API using Express.js and Prisma ORM which is really nice do I don't have to do deal with sql queries
If the API is hosted locally on the same machine as the bots network latency is going to be negligible
thats fair, could also be expanded onto other things
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
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)
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
the int of what exactly?
nvm and i mean len
you mean the len of all commands? im not sure how you would get the len of a command
how do i run a delete message ?
await ctx.message.delete() doesnt work
waiitttt
slash commands do that automatically
Iirc in slash commands it is inter.response.delete_original_message()
ephemeral messages need to be done to respond to the interaction
Or do the ephemeral
Yes
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
what?
how does a message become "done"
?
channel or author is missing
this is slash commands
ctx for slashes 😔
quite obvious
what library are you using
see above
why not just use main?
from what i could find discord.py doesnt have slash commands documented anywhere
check repo
they implemented slash commands a while ago
that looks like itd need me to do a total rewrite, whereas this so far has been a refactor
yes
lovely thing about dpy you need to make a whole rewrite because of all the new breaking changes
make an issue on the github and wait for a response i guess or ask in the support server if they have one
they do
what do you mean by "done"
!d disnake.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
they do have channels
they're not using disnake
i ment theyre needed
well, it was just to show them that "channels in slashes" do exist
do slash commands not have "authors" then?
Ofc
I already said that :)
!d discord.Interaction.user
The user or member that sent the interaction.
They have channel, author and message
why even have slashes when there cant be any author
its author for slashes
Anonymous User
user also works, so, uhhh
imagine
pardon?
oh wait, its an interaction too, I'm high
I'll get some sleep 😔 bye
Not surprising 
pardoned 😔
Lmao
ok
Hunter, what was the command to install the master branch for dpy 

pip install git+https://github.com/Rapptz/discord.py

already installed
thanks anyways
Then did u just want me to waste my energy and write that? 
Can u print ctx.author.id plz?
Also ctx.channel_id
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
This is also there tho
nah, I didnt want to open github to get the link of the repo, then copy paste the url, then go back to my terminal and write 3-4 words more and then paste the link then press enter 😔
channel_id isn't in the dictionary
Tf
Means the same thing as wasting my energy to save yours. Understandable 
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.

Don't become like Ash, only one annoyer is enough
take the conversation somewhere else
I better go away cry in a corner cya
wha
youre trying to index a dictionary with an object that isnt a key
There's a high probability that the channel ID in the dict is a string but interaction.channel_id returns an int
!e print({1: 2}[3])
@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
Remove the quotes lmao
Thats a string
?
not sure why they both said that
Nvm I'm most probably outta my mind
ok so the issue is? that the check fails because the key isnt in the dictionary?
yes
but then shoudlnt that not break?
define break
shouldnt the check return false and move on to the else
or is it more fundamental than that
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
if client.players.get(ctx.channel_id, None) is None:
return
``` this'll handle the keyerror for you
as before only the game active in a channel was per channel
!e
if "a" in {"a": 2}:
print("yup")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
yup
why not
if not client.players.get(ctx.channel_id, None):
return
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)`.
yes
append could be better because they're modifying a list inside of a dict
@glacial echo
add that to your code
My bad, sorry
then make it a key 

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])
how would the first if statement even work
!e
if 1 in {1: False} == False: print("Yep")
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
!e
if 1 in {2: False} == False: print("Yep")
@glacial echo :warning: Your eval job has completed with return code 0.
[No output]
U need True
Hm?
whatever datatype its getting, it sure as hell isnt a unique user id that is getting stored away anywhere
Show code
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)
what?
So, uhhh, what's the issue here?
here i ran /join_game twice in a row as the same user in the same channel
Ah
it has created a new "channel" key
That's why 
Stop using that lib and instead either use dpy master version or a fork like nextcord, disnake
use main!
Some part, yup
or disnake which you dont really need to do a rewrite
The module u r using rn has fucked up big time
and also the dpy main thing doesnt have any documentation that i can understand for slash commands
sorry, "interactions"
It does
it has documentation
just use disnake and it probably does
I cant understand it
!pypi disnake | @glacial echo heres docs https://docs.disnake.dev/en/latest/ext/commands/api.html#slash-command and examples https://github.com/DisnakeDev/disnake/tree/master/examples/slash_commands ofc if you dont want to do a rewrite
yay time to install a third discord api
atleast the creator wont archive the repo and then say he probably wont comeback and then comeback after 6months of chaos
but
i just installed disnake using the pip command they have on the installation page on the docs
restart your editor
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
Client doesnt support commands, Bot does
How tf did it work before tho
client = disnake.Client(case_insensitive = True)
ive been using this the whole time
U need commands.Bot
client = client whatever the fuck
How tf did that even work
...
but also it looks like i need to totally rewrite to use slash commands
interactions.py was far more simple than this but eh
Okay it's time for me to stop believing in reality anymore
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
Do one thing
You're not alone. Many people were frustrated that they have to re-write everything
Change the disnake.Client to commands.Bot after importing commands from disnake.ext
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
is a small uwu example
yes that
would raise an error
nice
intents expected Intents class from disnake but got given a discord class
Hmm
whatever uh
Wait
would probably raise something like intents must derive from Intents
write the whole traceback
nvm seems like disnake doesnt handle such a thing
it does
Also thought the same
are you using disnake?
yeps
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
mmmmmmm
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()```
It does check
why
my slash commands dont exist after setting test_guilds=[my_guild]
Czzz discord.py does?
why
Iirc it's guild_ids
test_guilds is in the bot constructor
Sadly idfk, would have been better if Danny allowed inputting the binary operators manually but well 🤷♂️
why
why ask him, when I ask you uwu
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
my bot no worky
no slash commands exist
use the guild_only deco
and the decorators are all wrong
you need to do client.slash_command
why ask him
because he made discord.py 
did you guys know that discord.py was previously called pydiscord?
no
thank
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
Cz me an idiot and never bothered to look into dark magic, aka, dpy's source
oof
dpys source isnt that advance you just need to dig into the 5 parent classes of each subclass
this is being fucky
nice
use slate two 
what
annnyyways
thats an overcomplicated command that doesnt really need a param rn as i have a single game
annnnyways part 2: electric booglaoo
the mebed is sent but then cant be edited?
fancy
thanks for that
currentembed is None
if you know its off topic why send it in the first place?
off-topic but relevant
as im working with slash commands and that makes slash commadns lok better
and makes it visually behave as expected
how make not none
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Is it possible increase font size of footer of embed?
No
afaik no, you can make it bold
can you?
No
Oo thats bad....
smh
Umm Ig I can let me try that
What I want exactly is a title of embed then a image and then some text

If I try adding field it gets added above the image so I thought to go with footer
is the text dynamic
Naah
Ill be adding a functionality soon to edit it too so that will create problem
dynamic image generation
Yea....I can do that!!PIL
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
Aha night man!!Have a good one
gonna update my trello and shut down
What shoupd I call my yggdrasil copy?
Totally Not A yggdrasil Twin
U know u should do everything step by step and tryna doing it all at once is just gonna frustrate u more 👀
not yggdrasil
thats actually a great idea
like literally what i said btw
thanks okimii
#include <iostream.h>
yes im awate
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
me when I had to shift my bot from dpy to disnake 😔
Not many changes
w o w, never did that much for bots
its not too frustrating now that i got everythign smoothed over as now its a few minor bumps and not just a fuckign cliff
?
jhbhjioferwgege
Just had a rough picture of what I need, in my mind that's it
the trello is to keep myself organized and allow my teacher to see my progress
nvm
You would still need to do those to shift to dpy 2.0
also making a new card directly in the completed tab to make myself fee laccomplished becasue i solved a problem that came up
Cool
well
Can't argue with that
not in the mood really
gott asay
disnake dev is pog, they actually wrote documentation and logical methods for writing slash commands
Hahaha
this was so painless once i figured out how to not be stupi
Cool
ohhh this is nice







