#discord-bots
1 messages · Page 68 of 1
Wanting to assemble a compact server
Oh golly
gee?
depends
If the bot has to cache a lot of users/channels/guilds and stuff like that, then it might use a fair chunk of memory
That's why I was thinking about jsons
Not to mention python isn't the most memory efficient language out there
Less ram, more space
?
I have no idea how to code on java
Storing all data in jsons
Ehhhhh, that still wouldn't improve your memory efficiency
probably would make things slower, since you would have to load the entire file into memory to read and write from it
💀
The bot has it's own internal cache where it stores user/chanels/message/guild objects
I need to build a server...
How many users does your bot have right now?
Well, I don't think it should use too much more memory
But I would highly suggest running it on something with a little more than 1gb
Then I guess stick with what you got until you do
Also
How does per server moderation work?
Mutes, bans, warns stack in one database for all servers?
I'd say when a mute or ban is stored, that guild id is also stored along with it, so that it can be associated with that server
There's many ways you could structure your database tbh
Databases like sqlite are similiar to spreadsheets, yes, in that they have columns and rows. Each column has a name, and a specific type of value it's expecting in it. You can add a row to the database, which contains actual data, corresponding to each of the columns
Are there any Verification Bots that use FB group membership to verify?
But with databases, you can do much more complex querries, and it's easier to move around and sort through data quicker
I need to watch some tutorials
Thanks for explaining
me when almost an hour with no messages
ok
🤔
why you're calling a Bot client? I mean client = commands.Bot(...)
yeahh^
Also you’re aware that get prefix is called each message?
Opening and closing a file each message is perhaps not the best idea
especially when it’s blocking
dunno
all tutorials do it like that
and it works
and for me it returns keyerror: "(id)"
why not
Because you get endlessly criticized by others for doing so
but why exactly
There's no harm whatsoever, I don't know where or why this useless convention started
anyways
are there any good discord bot writing guides
cuz documentation is for big brain
There are examples here: https://github.com/Rapptz/discord.py/tree/master/examples
But I don't know of any good guides as I haven't encountered any
All the guides I've come across as I was starting out were all terrible
first of all I need to know how to use sqlite to store bans, warns and mutes (with timer)
and literally there are no guides
For that you will need to refer to sqlite documentation
big brain advanced stuff 
sqlite isn't specifically made for another library (like discord.py or something). you will need to understand how both work and then make them work together
you can save yourself time by googling things instead of asking questions in a discord channel.
this channel is better suited for getting help regarding niche things or if you don't know where or how to start
getting better at doing your own research is a very useful skill in programming.
ok how to make a autoresponse cog?
just my two cents.
no idea what this means
can you elaborate?
a cog with functions that auto-respond to messages containing something exact
like image, text or emoji
basically, can I use event outside the main file?
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
yes I noticed in my frankenstein bot
but did not figure out how it works
can I setup cog commands only in specific channel(-s)?
You can use this decorator to register event listeners. Here's an arbitrary example for checking message content
class MyCog(commands.Cog):
@commands.Cog.listener()
async def on_message(self, message):
if message.content == 'hi':
message.channel.send('hello')
ty
This will send "hello" in the chat whenever someone says "hi"
and I can setup via sqlite custom responses?
Yes, but I don't use sqlite so I can't show an example.
You will have to do your own research or ask someone else for that :)

I want to make it so that you can reply to the bot and it recognises it and then sends a message, can I do this in 1.7.3 d.py
i don’t wanna interrupt- but it should be quick- how do you get the current guild the user uses a command in? a link to the docs is fine
discord.py, sorry
ctx.guild
I take it interaction.guild would work the same?
@commands.command()
async def guild(self, ctx):
await ctx.send(ctx.guild)```
yeah
this sends guild name
u can do whatever u want with it, store it, print it
thanks- sorry
whatever u need it for
Should’ve been able to figure that out myself lmao- but thank you so much ^^
no need to thank me
eh, I will anyway <3
I'm just here because I feel like eating rocks with how hard d.py 2.0 is
so I'm sticking with 1.7.3
someone help
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
I think this is what you're looking for
@scarlet aurora can you explain what you mean a little more?
are you talking about wait_for()?
this type of reply?
!d discord.Client.wait_for (or this?)
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Still a thing
yeah
@slate swan await self.bot.wait_for('message', check=check) works but is there a reply for this?
reply?
yes like this
if you want to reply to a message you should pass the message as the reference key-word argument to .send()
here's the docs for that method:
!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/latest/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/latest/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/latest/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/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
shortcut
well the .send() allows you to pass partial messages or message references
if message.reply works for you then great 👍
true, but if you're doing a wait_for you're probably getting a full message obj so might as well use it
ok fair
can you subclass aiohttp.ClientSession without ClientSession subclass object has no attribute '_connector'
ot but ClientSession strictly does not support subclassing
you should have gotten a warning
You'd be better off making a class to encapsulate a session rather than sub-classing ClientSession directly.
subclassing is deprecated though
also can you share the traceback?
i can't visualize this
Traceback (most recent call last):
File "c:\.vscode\Brala\Test.py", line 17, in <module>
asyncio.run(main())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "c:\.vscode\Brala\Test.py", line 11, in main
rjson = await client.get_player_data(id)
File "c:\.vscode\Brala\wrapper\brala.py", line 8, in get_player_data
response = await self.get(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 380, in _request
if self.closed:
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 963, in closed
return self._connector is None or self._connector.closed
AttributeError: 'BHClientSession' object has no attribute '_connector'
Exception ignored in: <function ClientSession.__del__ at 0x00000224F6C10B80>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 326, in __del__
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\aiohttp\client.py", line 963, in closed
AttributeError: 'BHClientSession' object has no attribute '_connector'
Can you show some code?
I could just make a new aiohttp.ClientSession everytime when making a call
but isn't that unfunctional
unfunctional?
import aiohttp
class BHClientSession(aiohttp.ClientSession):
def __init__(self, api_key):
self._key = api_key
async def get_player_data(self, id: int):
response = await self.get(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
return await response.json()
you aren't calling super().__init__()
now wait a minute
import aiohttp
class BHClient():
def __init__(self, api_key):
self._key = api_key
async def get_player_data(self, id: int):
async with aiohttp.ClientSession() as session:
response = await session.get(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
return await response.json()
I meant this before
it's not practical is it
instead of a creating a new session every time you can just create it once and re-use it
also i don't understand why you want to create it manually if you're only using it once and then disposing of it. just use aiohttp.request
so I add it as an argument to __init__ you said
no you didn't what the heck am I thinking
you said attribute
wait i'm not sure if this is a thing
You wanna be careful when constructing a new ClientSession inside of non-async functions.
ClientSession uses get_running_loop and that'll raise a RuntimeError when no loop is running
yes, i was going to get to this. it's fine as long as the event loop doesn't change
It is
no I wanna reuse it
Why not make a separate method to your class, an async-function that creates the session if it was not previously set?
This is very simple to do with hasattr
This is what I do
Hmm I’ve never thought of that. That’s pretty smart
class SomeClass:
session: aiohttp.ClientSession
async def setup(self) -> None:
if not hasattr(self, "session"):
self.session = aiohttp.ClientSession()
Then, inside of your request method, call this before hand to ensure self.session is defined
so now I did this
Optionally, you can do the hasattr check inside of your requesting method directly, but that's just a minor optimisation.
I got the json
what is that extension? To make vsc to look like that
after a couple of seconds I got this
just create a single request method like so:
import aiohttp
class BHClient():
def __init__(self, api_key):
self._key = api_key
self._session = None
async def _request(self, method: str, url: str, ...):
if self._session is None:
self._session = aiohttp.ClientSession(...)
resp = await self._session.request(method, url, ...)
# do something with "resp"
return ...
def get_player_data(self, id: int):
return self._request(f"https://api.brawlhalla.com/player/{id}/stats?api_key={self._key}")
that way you also have DRY code
(Don't Repeat Yourself)
This'll work great yea. Although I have qualms with setting _session as None (typehinting hell)
it should be fine, there's a type-guard
That's why I usually gravitate towards the hasattr method
When inside the context of _request yes, it'll be guarded. But when accessing it outside of that method
i don't see why you would need to
I'm gonna assume that your making a class not just for one endpoint? Otherwise the practically goes out the window
Or maybe you'd want to access it later by yourself, etc.
excuse me what
can someone tell me why this wont work
oh this happens just once the code ends so it's not really harmful
Do you have anything that keeps the loop running?
no
import asyncio
import datetime
import json
from wrapper import brala
client = brala.BHClientSession(key)
async def main():
id = 24737524
await client.create_session()
rjson = await client.get_player_data(id)
with open(f"stats-{id}-{datetime.datetime.utcnow().timestamp()}.json", "w") as f:
f.write(json.dumps(rjson, indent=2))
await asyncio.sleep(3)
asyncio.run(main())
Maybe use some temp measure ```py
while not client.closed:
await asyncio.sleep(0)
I wouldn't keep this in production code though
Yep, just wasn't sure whether or not you were gonna re-use
Error*
I'm just testing what I currently have
everything's gonna change here eventually
the only thing I need now is different functions for different requests
Which do I disable?
You should also add a context manager to your Client class
So you don't make people manually close the client rather ```py
async with Client() as client:
return await client.request(...)
but I wanna reuse the client
Yea, okay but that doesn't get affected by the context manager
oh
async with Client() as client:
await client.request(...)
await client.request(...)
await client.request(...)
return await client.request(...)
Within the context manager the client is re-usuable
It just closes when it exits the context manager
makes sense, unfortunately that's not what I meant
later I'm gonna use this API wrapper alongside with discord.py
and I'll want to use the same session with for example a command
that's used multiple times
Again
The context manager andy said is optional to use
Meaning you can have both the context manager way and the normal way

Hey guys for some reason my bot is sending 2 messages at once and i've noticed that the first message isn't even in the code but it was there before i saved and the 2nd one is the message after i saved
you didn't close an instance of the code running
where can someone help me with my code?
here
what IDE do you use?
so i can send my code with a error?
yes
Thonny on my raspberry pi
for this i need help
oh that's interesting
lemme try to research something
apparently you just have to click a stop button on thonny
and I assume he didn't miss that button
well
i stopped it
but it still didn't work i also tried running it in the console
yea i did that but it still does the same thing
cannot import name 'app_commands' from 'discord' - I'm trying to do slash commands but this isn't working.
Google isn't being helpful ;-; Does anyone know how to fix
pip install -U discord.py
thx
Dani i also tried to search on google but i couldn't find anything there
this is the error: typeerror init() missing 1 required keyword-only argument 'intents'
I can't think of anything else if that's not in your code anymore
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
yea i already did that
I also tried putting the file into somewhere else but still the same stuff
can you show your code?
replace nextcord with discord
k
from the looks of it, they aren't using nextcord
is it possible i could send the file per dms because i can't send all of it in this channel
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
but you can encounter the error where you're requesting intents you haven't enabled
I'm calling it
you will
why are people STILL making bots that use message commands?
message commands are classy
because they're honestly simpler
plus they've been around a long time, so people who are coming into it new are getting all the old guides and stuff with message commands
this only affects verified bots tho
i have tried with discord and the error is longer
Dani can i send the bot file in your dms tho because i can't send the whole text in here
i guess if you're making a bot for a personal server it doesn't matter
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
this do be a cloudflare block moment
oh
this doesn't really show the error
or does it
Whatever IP your replit is running on was probably blocked by cloudflare
what does cloudflare have to do with this
take a look in that html that's printed in the error
my brain will not focus right now
it shows the error
ok so dani i just tried to run it on my windows pc and there it's working so it must be something internal on the raspi
definitely
imma try reuploading the file onto the raspi
This isn't an error, it's a replit bug
what does 0.user do here
what can i do do remove that bug
it's less of a replit bug, and more of cloudflare spam protection I think
how is 0 bot though
no idea
i thought formatting a string is replacing {}
The best way to solve it is to not use replit, but you can probably get your replit to restart and get a different IP
it's a youtube tutorial thing to use this
it shows the tag of the bot
i nothing understand
Because it is 0th argument (if starting from 0) passed to format
i reuploaded the file and it's still the same i don't understand why tho
Idk properly but I used to use replit but I was getting that same error and it used to last for hours so i shifted to vsc
ohhh thanks, that makes sense
You can't, that's what you have to deal with if you are gonna use replit, better shift over to other ide's
which one?
!e
print("this will print banana... {0}".format("banana", "apple"))
can you like check the source code for the format method of str
The long error, html one
dont understand
replits run on shared machines, which means that there are a bunch of people's replits out there with the same IP address. If a bunch of those are running discord bot's, some of them possibly even breaking or abusing ratelimits, cloudflare or discord might start blocking requests like you see in your replit
You dont understand English? 😶🌫️
This error
This isn't right btw
no i mean if you say to shift to other than replit
Like visual studio code or pycharm or sublime, you have many good options
most likely abusing i'd say. you wouldn't host a bot on your own network if you were
You gotta have 2 intents enabled, this isn't right, you gotta enable members intent and message_content intent
hmm i have visual studio code
but never used
Convert to it, people in here will help you for sure
the issue will be hosting right after
it was never where you edit the code
it's where you run it
Uptime robot ain't a good source for hosting tho
It's best to get a student vps and use it
!vps
Ight 💀
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
Replit have way too many bugs and it gives it in the form of errors, most of time, people who use replit are beginners and they don't understand it. Moreover discord automatically bans your bot for few minutes or hours for ratelimiting
Dani i also tried looking if there's another instance running but there is only one so now i'm even more confused
What's the error? And Dani said he's going offline btw
cloudfare does the ratelimits https://discord.com/developers/docs/topics/rate-limits#invalid-request-limit-aka-cloudflare-bans
yeah thought so
thats why some bots get HTML response when ratelimited, iirc its just HTML body that says youre being ratelimited, cloudflare sends it
oh alr well my problem is that my bot sends the message of the old save and then the message of the new save so then i have 2 messages with a few changes i'm running the bot on a raspberry pi btw
Oh-
so when you stop the file from running, do you get any response from the bot when using a command?
Hmmmm i recently got that banned for 15 mins for rate limiting but it just said something around "you are being banned by discord for ratelimiting, pls read the docs to not get this in the future" and it provided some docs, as far as I remember, it didn't have any html body
yes i do for some reason
then you still have a process running
just to point out i already tried restarting it
yeah but thats just limiting iirc the HTML body gets sent uppon being temporary banned
is your RPI the only one hosting the script?
you're not hosting it locally?
i am hosting it locally but there might be something still running it
well, then there's your problem ofc
you know what to look for
what IDE are you using?
Dk about other ide's but it ain't the same with replit tho, html body error is kinda random, it wasn't there earlier tho, i used it like a year ago and came back to it last month then I kept getting that html errors very frequently for no reason so I shifted over to vsc, as far as I remember
Thonny on RPI and PyCharm on PC
Why are you using 2 tho? Just wondering 😶🌫️
pycharm can run multiple files, make sure in the top right, when clicking the dropdown of your files, you only have one
so it's not like shitbot(1)
the only time an HTTP request to discord returns an HTML body saying you got limited is when cloudfare filters/ignores/blocks your traffic(HTTP requests)
well when i wanna do a hotfix i do it on my pi and if i wanna add some new stuff i do it on my pc and SniperGlitcherz i don't have pycharm opened
Yeah yeah, what you are saying is right but replit is different-
but i noticed the replit was on 💀
in what way?
you should use github for this kind of stuff
and then just pull on your rpi
although i turned it off
there's basically still some process running somewhere ofc, for you to find out
Ugh nvm dude
?
<!DOCTYPE html> or something iirc
well but how do i do that tho?
Don't even have my pc near me to check 💀
thats just saying its an HTML body?
simplest way is just restart your pc
Ok
nah i mean to pull the github onto my pi and the process was replit it was still on for some reason
it still returns HTML, like when you e.g make a request to a url like https://youtube.com
well, you only mentioned hosting it on your rpi and locally to me, so yeah
You get ratelimited by replit, not by discord or cloudfare
well, you should first of all put your project on a repo on github and learn basic git push commit and pull stuff
No?
Why would replit ratelimit your traffic?
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f":warn: {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)```
can someone tell me why em is an error
its in a cog btw
Em should be indented
It's missing an indent
everything that you want to be under that if statement should be indented
including the await ctx.send()
wdym "indented"
!indents
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
i dont find a secrets to hide token in VSC
Did you go and call the discord api a bunch to get this or did you just copy it from somewhere 
You can use .env? No? New to vsc tho
yes
With .env files, you'll need to use the python-dotenv package or something similar to load them
unless vsc has some kind of thing for that i'm not aware of
Hello! I'm brand new to making bots and I'm learning slash commands.
I was wondering how can I get the bot to get the guild ID so my friends can also use the bots in their discords.
This is why I have but I'm completely lost
Idk man, there's this thing called "freecodecamp" i started using replit because of them and in their forum, they said that replit started ratelimiting as many people started using it lately
i doubt ratelimiting would be done its probably traffic filters
or something along the lines
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
@commands.has_permissions(manage_channels = True)
async def lock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
await ctx.send(embed=em)
@lock.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
@commands.command()
@commands.has_permissions(manage_channels = True)
async def unlock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
await ctx.send(embed=em)
@unlock.error
async def unlock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
def setup(client):
client.add_cog(Moderation(client))```
Setup func should be out of your class and it should be async def and add_cog should be awaited
You are right ig
So the end part should be in main.py? Or what
i literally got no experience with git and is there maybe a tutorial on yt? i tried searching it but i couldn't find anything
basically version control, great for keeping track of shit
are you even connected / are you committing?
No it should be in the same file but not in class block
haven't seen any code, can't say
So where do I put it?
class Moderation (commands.Cog):
Your code....
async def setup(client):
await client.add_cog(Moderation (client))
from discord.ext import commands
class Moderation (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
@commands.has_permissions(manage_channels = True)
async def lock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
await ctx.send(embed=em)
@lock.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
@commands.command()
@commands.has_permissions(manage_channels = True)
async def unlock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
await ctx.send(embed=em)
@unlock.error
async def unlock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
def setup(client):
client.add_cog(Moderation(client))```
same error in terminal
What did you even change bruh
I literally gave you the code and yet 🥲
This last part, the setup thing is called a function, it should be out of the class block as in remove the indents and add async before def and await before client.add_cog
from discord.ext import commands
class Moderation (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
@commands.has_permissions(manage_channels = True)
async def lock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
await ctx.send(embed=em)
@lock.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
@commands.command()
@commands.has_permissions(manage_channels = True)
async def unlock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
await ctx.send(embed=em)
@unlock.error
async def unlock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
async def setup(client):
await client.add_cog(Moderation (client))```
Yea
that warning most likely means you're still using dpy 1.7.3 and not 2.0, since 1.7 expects setup to be a regular def function
Either way, it was in the class block
sure
💀
How do I upgrade again
py -m pip install -U discord.py, -U telling pip it should upgrade the package
So I have an issue and I'm not sure whats wrong. Does anyone know what this means?
Traceback (most recent call last):
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "c:\Users\13129\Documents\slash-main\Slash.py", line 55, in ben
await interaction.response.send_message(random.choice(ben))
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
TypeError: object of type 'Command' has no len()
Traceback (most recent call last):
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\13129\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 865, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ben' raised an exception: TypeError: object of type 'Command' has no len()```
import discord
from discord.ext import commands
import os
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=",", help_command=None, intents=intents)
@client.event
async def on_ready():
print("vital is ready")
print("--------------")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you.."))
from discord.gateway import DiscordWebSocket
class MyDiscordWebSocket(DiscordWebSocket):
async def send_as_json(self, data):
if data.get('op') == self.IDENTIFY:
if data.get('d', {}).get('properties', {}).get('$browser') is not None:
data['d']['properties']['$browser'] = 'Discord Android'
data['d']['properties']['$device'] = 'Discord Android'
await super().send_as_json(data)
DiscordWebSocket.from_client = MyDiscordWebSocket.from_client
initial_extentions = []
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
initial_extentions.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extention in initial_extentions:
client.load_extension(extention)
client.run(BOTTOKEN)``` Main.py btw
erm
why are you doing it this way?
Wdym this way
This is like, messing with the internals
Are you just trying to set a custom browser and device metadata?
?? I’m making a discord bot
from discord.gateway import DiscordWebSocket
class MyDiscordWebSocket(DiscordWebSocket):
async def send_as_json(self, data):
if data.get('op') == self.IDENTIFY:
if data.get('d', {}).get('properties', {}).get('$browser') is not None:
data['d']['properties']['$browser'] = 'Discord Android'
data['d']['properties']['$device'] = 'Discord Android'
await super().send_as_json(data)
DiscordWebSocket.from_client = MyDiscordWebSocket.from_client
you can remove this entire part
Not sure why you're overriding internals to send custom metadata
Ah yeah that
But sure
Not sure if we can help with that as it might be bordering on rule 5
It's not documented usage, sort of a gray area
Oh really I can just use normal status
That would make things much much simpler
Yea I’ll do that rn
Not worth it just for "cosmetic" appearance
from mimetypes import init
import discord
from discord.ext import commands
import os
from apikeys import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=",", help_command=None, intents=intents)
@client.event
async def on_ready():
print("vital is ready")
print("--------------")
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you.."))
initial_extentions = []
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
initial_extentions.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extention in initial_extentions:
client.load_extension(extention)
client.run(BOTTOKEN)```
is what i have now
That's much better
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
initial_extentions.append("cogs." + filename[:-3])
if __name__ == '__main__':
for extention in initial_extentions:
client.load_extension(extention)
can also be combined into one for loop
I wouldnt say that its a gray area tbh more like an unknow one, its not documented nor is their any rules about it nor does any apply to it exactly
so its not really something againts TOS or anything its just discord hasnt given much attention about it afaik
replace with that?
but i would agree its a bit hard to get it by editing internals and isnt really worth it (just make your own wrapper)
what is this?
from discord.ext import commands
class Moderation (commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.command()
@commands.has_permissions(manage_channels = True)
async def lock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = False)
em = discord.Embed(colour = discord.Color.random(), description=f"{ctx.author.mention} is now locked")
await ctx.send(embed=em)
@lock.error
async def lock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
@commands.command()
@commands.has_permissions(manage_channels = True)
async def unlock(self, ctx):
await ctx.channel.set_permissiona(ctx.guild.default_role, send_messages = True)
em = discord.Embed(colour = discord.Color.random, description=f"{ctx.author.mention} is now unlocked")
await ctx.send(embed=em)
@unlock.error
async def unlock_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(colour=discord.Color.orange(), description=f" {ctx.author.mention}: You're **missing** permission: ``manage_channels``")
await ctx.send(embed=em)
async def setup(client):
await client.add_cog(Moderation (client))``` Idk why my commands wont work
just logging
make sure you have message content intents enabled
I have them enabled
Can I see them?
!intents The discord developer page
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Yeah you don't have message content intent enabled
I do tho
intents.message_content = True in your code to enable it
why are those errors??
if you hover over them they'll tell you what's wrong
you should always fix those errors
intents = Intents.default()
is says Intents is not defined by pylance
Yes because it doesn't know what Intents is
You have to tell it what it is
You can either import it from the discord module (not recommended due to namespace pollution)
or you can use discord.Intents.default() (recommended)
And setting the message content flag to true after you've passed it into the bot is the same as not passing it in at all
Well now you're not saving discord.Intents.default() anywhere
it just makes the object and throws it away
why does it do that bru
because it's not defined
Hi, Robin u still here? I woke up just now
You're telling python, "hey, make this object, but just throw it away once you're done. don't worry about it." then later, you're asking it "remember the object that you threw out? can you get it for me" and python can't, it's in the trashcan
morning, what's up?
good, wbu
not much, i'm about to head off to bed lol
oh lol
better funnier way
user: declare this value
python: ok
user: remember that value i gave you?
python: um.... which one? you never made a variable to make a pointer to point to that memory address that has that value.....
I dont no why but in one channel of my server , search thing not working, like it show 3-4 days back searches
How can I fix it
reminds me of
Like a squirrel hiding it's nuts in the ground somewhere, the forgetting where it hid it
RecursiveError
Hey Robin! I need some help with an error in github workflows. Do u mind helping me in #ot2-never-nester’s-nightmare?
I'd love to, but honestly GH workflows are out of my expertise and i kinda feel like hitting the hay rn lmao
Oh haha all cool. Have a good one!
plot twist he never had a nut int* nut = nullptr;
yo, is discord.py compatible with ironPython??
Isn't iP still in like 3.4 or smth?
I trying use c++ with python, but the only directly way what I found, is with Ironpython
uwu
Tbh no one has really tried, but you should give it a try!
you could make use of this: https://dpp.dev/
just, don't hassle if you speak c++
right, haha, i'll try
ok, thanks
bruh, I never see this lib in my life, but, i'll try with it
there's a library for everything by now
@crimson frigate highly unlikely it will work. Because iP targets Python 3.6

wth is that
girlfriend haha
it's NSFW, and not appropriate here
Sorry!
what if you put girlfriend and boyfriend in the same env
OSError
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Discum is a self bot lib
still breaks ToS
!pypi discum
you are still braking ToS
'laws' 🤓
how is this not banned btw
Well it was probably made before self bots were not allowed + discord probably can’t just ban a package
goofy discord
?
@client.command()
async def hangman(ctx):
r = RandomWords()
word = r.get_random_word(hasDictionaryDef="true")
length = len(word)
data = dictionarysearch(word)
print(data[0])
for char in word:
word.replace(char,'_')
mbed = discord.Embed(
title=f"Length of Word: {length} Reply to guess",
description = f"{word}"
)
await ctx.channel.send(embed=mbed)
``` literally nothing happens. also the word is generated, i just want to replace all the letters of the word with underscore and then display
so you execute hangman and nothing happens? no error?
by the way, you can use ctx.send
ik
what is RandomWords
is that a library?
!pypi Random-Word
yes
faker is better bro
what is faker
!pip faker
!pypi faker
how do i get random word i can see names and adreses
Idk man try finding
I actually can't find that in faker
Brah let me find
what is dictionarysearch?
under = "_"*len(word)
oh
use pydictionary
def dictionarysearch(word):
api = "https://api.dictionaryapi.dev/api/v2/entries/en/"+word
r = requests.get(api)
json_data = r.json()
return json_data
!pypi pydictionary
how long u searched for it berh
h
i just want to resolve my problem, it works when i dont add the for loop
but when i do it does not work
i need it to replace the chars with "_"
@tropic burrow
ok
imagine using for loop 😔
under = "".join(["_" for i in range(len(word))])
lol
nothing happened
under = "_"*length
mbed = discord.Embed(
title=f"Length of Word: {length} Reply to guess",
description = f"{under}"
)
await ctx.channel.send(embed=mbed)
indentation?
replit 😭
did you restart
restart what
The program
bot
or reload extension
well this doesnt look like a cog
and use await ctx.send
Isnt a cog bro
send the whole command code
Hi! I have an event that doesn't work and idk why
@bot.event
async def on_message(message):
channel = bot.get_channel(997568539223396502)
salts = bot.get_user(480341304799395840)
await salts.send(f"{message.author.name} >> {message.content}")
await bot.process_commands(message)```
Do you have multiple on message events
Yes
that's why
But i added a await bot.process_commands(message) so it should work?
make them a listen
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
it's 2 lines you have to change
Oh
there's an example on site too
@listen(name=on_message)?
@bot.event -> @bot.listen()
Thanks
Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T
Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Community songs server >> Saltss_ >> T``` holy shit
It keeps repeating this
if it's all in same file just put them under one on_message 💀
what other shit do u have
it's probably responding to its own message
yeah
thats what ur message is about
u have to add a check if message.author.bot: return and if message.guild is None: return
so it doesn't reply to itself ^
on message doesn't just look in servers
worked kinda but how to space the underscores
ok
like this?
@shrewd apex
this is whats happening when i do that
literally nothing comes in the description of the embed
show
Hello everyone, I have a question, how can I request a picture from a person when he enters a command? (The essence of the bot is a person enters a command and throws his picture, after that the bot sets up another one on this picture) The modules that will be used are
discord py (nextcord maybe)
and pillow
I was already told what argument to write something that asked for a picture, but to be honest, I did not understand how to apply it, the distortion in the documentation did not find anything
I am trying to add a role to a user when a specific message is reacted to. I tried to do something like this but it is not working for me.
@client.event
async def on_raw_reaction_add(payload):
ourMessageID = 1014040026444730388
if ourMessageID == payload.message_id:
emoji = payload.emoji.name
if emoji == ('✅'):
role = discord.utils.get(guild_id.roles, name="Shawnland")
elif emoji == ('👎'):
role = discord.utils.get(guild_id.roles, name = 'Verification')
await member.add_roles(role)
I assume the user has to attach a picture being non-animated in the format of .webm .jpg .png
Message object has an attachment attribute that returns a list in any library that is the same.
To be honest, I don’t quite know what this argument is and how to use it.
like, I would just like to know the argument that allows you to upload a picture
Does it pass the first if? Could you check?
Well like I said the Message object will contain said attachment. You would also need to verify the file type using MIME, that's what I recommend.
You would need to run pillow in an async executor inside that edit said image then return the result.
yes when I add this it goes through, so my issue is assigning the role. when I type await member.add_roles(<roleid>) it has a line underneath the members. Also doesnt work with user. Im assuming its because payload
if emoji == ('✅'):
print("HellO")
I don’t quite understand how the attachment needs to be entered or what its name is so that it only accepts pictures. About MIME it's ok
Okay but how is member defined?
Pretty sure payload has a member attribute but you don't have that yet.
Thus payload.member
Well you have to do the following checks, check if an image is attached. If not message.attachments will be empty, so False. Then you could check the name but we don't want people breaking the bot so instead of checking the file extension we will check the file type using MIME. If we're sure it's a valid static image you can process it.
@commands.command()
async def img(CTX: commands.Context, image: discord.Attachment):
...
image here is ur attachment
thx
Since when is there an attachment converter?
there is now
lmao
i used it in my hybrid commands
What lib?
class discord.Attachment```
Represents an attachment from Discord.
str(x) Returns the URL of the attachment.
x == y Checks if the attachment is equal to another attachment.
x != y Checks if the attachment is not equal to another attachment.
hash(x) Returns the hash of the attachment.
Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") and is hashable.

okay so await payload.member.add_roles(<role id>) the <role id> isnt calling the role. Am I suppose to do it a different way?
Well add_roles so you need to pass a list.
list of discord role objects or just a single role object will also do
They also need to be role objects or snowflakes.
await payload.member.add_roles(discord.Object(<role id>))
In this case Object will just create a snowflake here since they only need the ID to assign the role.
Thank you ❤️
so pydictionary isnt working on replit for some reason, so i have to use an dictionary api. why does this not work
def dictionarysearch(word):
api = "https://api.dictionaryapi.dev/api/v2/entries/en/"+word
r = requests.get(api)
json_data = r.json()
return json_data
@client.command()
async def hangman(ctx):
r = RandomWords()
word = r.get_random_word(hasDictionaryDef="true")
length = len(word)
data = dictionarysearch(word)
print(data[0]["meanings"])
under = "-"*length
mbed = discord.Embed(
title=f"Length of Word: {length} Reply to guess",
description=f"{under}"
)
await ctx.channel.send(embed=mbed)
guys could anyone advise me
how to write an error handling if someone put text value !solana?
because i wrote simple function which converts solana to my local currency which is pln
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, message_content = True)
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def solana(ctx, arg:float):
result = round(arg * float(pricesol) * float(pricezl))
await ctx.send('Your {x} solas are worth {result}zł'.format(result=result, x=arg))
bot.run("token")
i have code which scrap values of sol and usdt above ^^
but im wondering how i could write error handling if someone will something like !solana kekw, because basically this type hint arg:float change every type of data to the float
!d discord.ext.commands.BadArgument
exception discord.ext.commands.BadArgument(message=None, *args)```
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
raise this and catch it in the error handler
i dont understand the path of the returned json (how to express in python) and sometimes it doesn't even work at alll
Is it possible to insert an image in discord modals?
not for now
Cogs are a discord.py feature that allows you to divide your commands into seperate categories constructed using classes.
you can have cogs in different files rather than a single bot file
!d discord.ext.commands.Cog here's how you use them
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
only selectmenus and even that dosent show up on phone maybe it will in the new discord mobile client but i didn't try
yes kinda its like handy plug-in
discord/ext/commands/bot.py lines 939 to 943
try:
setup = getattr(lib, 'setup')
except AttributeError:
del sys.modules[key]
raise errors.NoEntryPointError(key)```
i'm hosting my discord bot on windows, but i want to host it on linux. but this code is not working. can anyone help me?
token = json.load(open('data\\config.json'))['token']` #code that dont work on linux```
whole bot code
import discord
from discord.utils import get
from discord.ext import commands, tasks
from discord import Intents
import discord.ext
import discord.ext.commands
from discord.ext.commands import has_permissions, MissingPermissions
import aiohttp
import sys
from datetime import datetime
import sqlite3
import requests
import random
import json
import time
import os
prefix = json.load(open('data\config.json'))['prefix']
token = json.load(open('data\config.json'))['token']
all bot command here
if name == "main":
client.run(token)
because Unix uses forward slashes, not back slashes
replace \\ with /
np
Wdym by you get your own unique answer
so that when you click on the first 3 options. Each option gave out its own version that you will write to him
example. When you click on the Основные option, the bot writes 123 to you. When you click on the Модерация option, the bot writes 765.
@tawdry tendon
Ahhh
пример. При нажатие на вариант Основные бот тебе пишет 123. При нажатии на вариант Модерация бот пишет 765.
I don’t understand that but ok
do you even know what a select menu is!?
Anyways, I did this with a dropdown it’s probably similar, so give the button a value and if that value is clicked then send something
I have a bot too, with a dropdown
well, I need this list to have feedback when clicked, it gives out certain messages!!!
discord.SelectOption(label="Math Command", description="View math commands", value="value1")
Can you send me backsticks
I’m on mobile rn
@slate swan
?????
!code
Ik what your saying
how to make the bot respond to you when you click on the list item. But so that the answer is not the same, but with different options !?
Is it dropdown or buttons
???
!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.
the list that is select menu!!!!
Ok
the select menu list is displayed. You click on one option you get a message
discord.SelectOption(label="Math Command", description="View math commands", value="value1") ```
That’s the option
And for it to respond , I gave it the value “1”
Or you can use the label but just use value for this
And this is to respond
async def select_callback(self, interaction, select):
if select.values[0] == "value1":
await interaction.response.send_message(embed=mathembed)
And in the send_message you can type whatever you want or make an embed
Do you understand now
and this message can be duplicated so that each variant of the list has its own message ?
Yes
Add a different value to each option and send whatever you want in it
What’s the error
Can you send ONLY the part where the error is
I don’t mean like that
Like show the code where the error is
if select.values[2] == "value3":
self.values
if select.values[0]
Or you can do that, but I did it with select
it wont work coz u need the class object
It does work
async def select_callback(self, interaction, select):
if select.values[0] == "value1":
await interaction.response.send_message(embed=mathembed)```
like that it will work
callback has no positional arg select
@shrewd apexhow to make a message appear when clicking on the options in the list. The message should not be the same. And the different options
so what u sent won't work
use interaction.response and interaction.data to determine what was pressed
how do i like make a system to check for replies for the message the bot set
how is it implemented!?
for example
@client.command()
async def hangman(ctx):
r = RandomWords()
word = r.get_random_word(hasDictionaryDef="true")
length = len(word)
data = dictionarysearch(word)
print(word)
meaning = data[0]["meanings"][0]["definitions"][0]["definition"]
under = "-"*length
mbed = discord.Embed(
title=f"Length of Word: {length} Reply to guess",
description=f"{under}"
)
sentmsg = await ctx.channel.send(embed=mbed)
there has to be some message to check for replies for sentmsg
@tropic burrow dude. It's useless to ask something here, I've probably been asking the same thing for 5 hours and they can't answer me how to do it all the time they say what I've already done!!!
I don't understand what language I need to communicate with you here!?
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
You can wait for an on_message event and in the check see if the message.reference is same as sentmsg
wait
intents = Intents.default()
intents.members = True
bot=commands.Bot(command_prefix = ".", intents = discord.Intents.all())
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
The site also includes all intents, what's the problem?
you know hangman right? so basically i want the user to reply to embed message and check if the message content is in the random word
Ur doing Intents.all() in code so u need to enable all privileged intents in dev portal
Message content, presences and members
@tawdry tendondon't reply to my messages anymore. You're writing what I've already done. If you don't understand what I want to do, don't get in the way
u tell me how many callbacks do u think a selectmenu can have?
It's all inclusive too.
as many as you want
Can you verify you have saved changes after enabling the intents?
its simple python do i have to write the code down and spoon feed u u just need to have a if statement and check which option was pressed with custom id and customise ur message
well gl with that 🙏
Maybe u shld be less piece of shit then PPL will help u
@meager chasm the example i saw in the read the docs is only for a ON message thing. How do i make for a command
U wait for message event
And call wait_for in the command
Please make sure you're using the right bot token (the one that has the intents enabled on the developer site) That'll be the only other reason why it's producing an error like the one you are experiencing
can i do @client.event in a @client.command?
Why would u do that
nope
nice helped...
why not use @bot.command
coz he defined client = bot yt i think
lmao
yes
💀

that is allow in python
@shrewd apex how to make several options for the message that the select menu can give when clicking on the items in the list!?
Now the bot works, but gives an error, the token has changed, but still gives...
discord.client: logging in using static token
discord.gateway: Shard ID None has connected to Gateway (Session ID: 77650add909b1a30d04d6595abb600a8).
U can give it function to filter out which event to capture
See example in docs
That is not error
This is a debug log, and it says to me that the bot is running fine? That being a non-sharded client has been connected to the gateway
you have to join the bot include 1 thing like intents something like this
u can just use the value param for options and get the value from interaction.data
quick unrelated question does isinstance() return true or false
By the way, about the static token, I don’t have such an error in the nextcord library when I do something with classes, but in discord.py there is
isinstance with what
Oh u mean does it return bool
i know
class Dropdown(discord.ui.Select):
def __init__(self):
# Set the options that will be presented inside the dropdown
options = [
discord.SelectOption(label = "Основные", emoji= ":large_blue_diamond:", description= "Основные команды сервера", value="value1"),
discord.SelectOption(label = "Модерация", emoji= ":large_blue_diamond:", description= "Команды для модерирования сервера", value="value2"),
discord.SelectOption(label = "Взаимодействие", emoji= ":large_blue_diamond:", description= "Команды взаимодействия между участниками", value="value3"),
discord.SelectOption(label = "Экономика", emoji= ":large_blue_diamond:", description= "Команды связаные с экономикой", value="value4"),
discord.SelectOption(label = "Настройки", emoji= ":large_blue_diamond:", description= "Команды настройки", value="value5")
]
super().__init__(placeholder='Список команд сервера', min_values=0, max_values=5, options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "value1":
await interaction.response.send_message(
embed = discord.Embed(description= f'{self.values[0]}', colour=0xF1C40F),
delete_after=60
)
if self.values[0] == "value2":
await interaction.response.send_message(
embed = discord.Embed(description= f' {self.values[1]}', colour=0xF1C40F),
delete_after=60
)
if self.values[0] == "value3":
await interaction.response.send_message(
embed = discord.Embed(description= f' {self.values[2]}', colour=0xF1C40F),
delete_after=60
)
does not work
Yes it does
But you referenced it as an error in your message?
this is selectMenu?
U can change discord py default logging if u don't like it
yesyes
!d discord.SelectOption
class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.
These can be created by users.
New in version 2.0.
use the value kwarg bruh
u are not even trying to understand
u are just crying its not working from past 15 mins
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
@shrewd apexand how the fuck to understand it!?
Do u know object oriented programming?
by getting some common sense, patience and knowing some python basics
what search
no you havent, look carefully
its literally different smh
...
{'values': ['value1'], 'custom_id': '909cf52baeefd032e83d88dd00fbbc67', 'component_type': 3}
does this work?
def check(m):
return m.content in word and m.channel == ctx.channel
msg = await client.wait_for('message',check=check)
yes so now u know how to parse ur values?
now u know which option was pressed use this info
yess if word is defined
btw the m.content in word is for hangman
this is word
word = r.get_random_word(hasDictionaryDef="true")
yeah ffa
ic
I'll laugh when the next time the doctor gives you a plantain instead of medicine and says put it where it hurts
actually wait this wont work at all
i have to send something if they are wrong
so i will remove the m.content in word
well, it's done and still everything works the same as it worked before...
yeah and I'll hope that teachers in school gave the answer key instead of the question paper for exams
Yeah and u can then put the wait_for in loop and break when u get right answer
You can raise an error in the check and handle it 
while loops brokes in async functions
it doesn't
well, you probably have the addition of natural numbers studied in schools up to 1653 classes. Because you probably have to explain it in silence
why ?
but actually u can just use a try except for this
x = wait_for()
try:
...
except asyncio.TimeoutError:
...
else:
...
will this work
What
def check(m):
if m not in word:
await ctx.send("Wrong!")
else:
return ctx.channel == m.channel
msg = await client.wait_for('message',check=check)
wait i should return something
Well not rlly u can't await in normal function
if m is not in wor
wait_for raises a Timeout, so the while will loop until the timeout is reached
U can set timeout to None
so i make it async?
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
I don't think check can be async
<@&831776746206265384> this guy kinda being a jerk
@shrewd apex Please respect other members.
...
check cant be async?
I'm sorry, but he was being rude right before a Mod ping. 😉
I sont think so u can try
if m not in word:
await ctx.send("Wrong!")
return False
else:
return ctx.channel == m.channel
```
@hollow badger I think this is an insult
what happens if it is false?
nothing its passed
nothing, it will wait for the next event that you're handling
while True:
msg = wait_for()
if word in msg.content:
break
else:
send('wrong!!!')
``` is waht i thinking
so after the ctx.send nothing happens
wait
Guys, is @task.loop() working for your bots?
You have been a little disruptive just reading back. I suggest you ignore each other or spend time on another channel for a bit.
Yees
u have to break the while true loop somehow
but what will check function be then
otherwise it will just run on
Yes that is what break do
break will exit while loop and go to next code
If there is ever a concern you can ping Mods or open a thread with the ModMail bot by DMing it.
I've just been trying to get a normal answer to the question for 5 hours. And such as they give their wrong advice
yeah but if he keeps answering wrong the while loop wont end
there is no check for timeout either
bruh with that you will just call a lot of wait_for 
timeout can be None !!
I triend using the API reference for discord.ext.tasks, and it doesn't work, here's the code
class MyCog(commands.Cog):
def __init__(self):
self.index = 0
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
bot = MyCog()
Wasnt really a concern but the environment really wasnt friendly
Ok so why that is bad
And he can change it if he wants
Not every question gets an answer. You may be better coming back a different day rather than being disruptive.
well indeed
but its for hangman
Just checking channel
With a None timeout that wait_for will run untill the websocket is dispatched
What is wrong with calling wait_for
It will block till message event which satisfies check is dispatched yes
if you add a check that will mean, when the check is passed, you will have your bot to response n times as n = times wait_for was called in that while loop
It only blocks the task so it doesn't matter
so let's make an example you do 9 fails and then print the correct answer
you will read 10 times the correct message
What!! No
cuz all that wait_for will be dispatched when the check is passed
actually let him just try it he can change it later to what i sent before according to his wishes
no wtf
wait cant i just do something like !hangman [insert number of guesses here] and then break the loop when guesses is 0?
It not calling 10 wait_for
and say like the guy was hanged
u can
bruh what a while does?
loops while condition is True
it will be firing a wait_for after every attempt
ok im adding a guess
it doesn't mean anything, the wait_for waits for an event, it does not metter where you call it
parameter
an event will be always dispatched
Correct that's how it should be

wait
well actually endysis is not wrong this setup can be used if u want to limit the number of guesses or set the number of guesses
also @meager chasm why would i break it if the guess is right?
because i have to continue the guess game
shouldn't i use put a check and then use continue if not all letters have been guesses
there's only one api to make discord Bots and it's the official discord's Api