#discord-bots
1 messages Β· Page 1144 of 1
terminal based text editor
Zeffo what was that
#editors-ides tho it's kinda dead so offtop or general
Based text editor ?
Very based
Ok ill install it
you edit code from ur terminal, that is what i meant
oh
Red pilled ?
bro stop it, we all know
sorry
motherfucker isnt a racial slur anyways
sorry?
My bad
It's a parental slur, are you trying to perhaps justify it?
Neo vim looks hard to learn
let's bring it back to discord bots
They like birch so much
Ok
this server jfc
.topic
Im making a multi purpose discord bot
good
it is, but once you learn it, you will be extra productive
No god please no
sorry ryuga π i wont do it again
Bad word filter im making right now but it doesnt work
could you send the code and error
I have a bunch of word filter algs
great
its alr π
We are talking so nice about discord bots
Bad word filters are a pet hate of mine, because they're rarely ever implemented correctly, and even when they are they're usually used incorrectly anyway
same
then give a robust alternative ig?
It's needed for keeping out bad words
Guys i've heard this reg ex is good for filtering bad words?
its mostly any(word in message for word in bad_words)
which is not the way to check
What is it?
penistone moment
fΓΊck fΓΌck fΕ±ck
Regular expressions
Tutorial?
$hit
There are a bunch of them including python docs
And put them in the woodpile for maximum efficiency
@cold sonnet you should try my word filter π
Γitch
The way Discord's new bad word filter is implemented is decent, it is based off whole words with the possibility to add wildcards
it's not perfect but for Discord's scale it's not a half bad solution
regex is a tool which allows you search for complex patterns inside strings, the way you access them in python is using the re module
Ohhh that sounds good for filtering words))
Tutorial?
um i wouldn't use it for that, but you can check this out (https://www.javatpoint.com/regex)
Some word filters I made if anyone's interested https://github.com/Exenifix/AIAS/blob/master/utils/filters/blacklist.py
No way it got 4 stars π³
That is good does it work for woodpile words?
https://www.regular-expressions.info/tutorial.html
that has examples in java, you can check this out instead
that symbol mask you have, this might help: https://github.com/vcokltfre/normalize/blob/master/normalize/letters.yml
Does it delete woodpile words
Thanks
what are woodpile words
Tho I mostly rely on character whitelist
wtf
The what
Also no htat is not a slur i censored it
!mute 995719300344205342 I said to move on to discord bots
:incoming_envelope: :ok_hand: applied mute to @lilac mica until <t:1657474685:f> (59 minutes and 59 seconds).
I think they wanted to know a way to implement a filter for such phrases
yep
let me discuss something with them in modmail
rip
Well if you get unmuted the answer is no. The only way you can reasonably determine that is human moderation, but frankly for racial slurs I'd take the stance of removing them regardless of context, allowing them has so many more downsides than advantages
imma go have dinner π
bye π
doxxxxing
Don't tell me u made that manually
π
I spent a lot of hours scrolling through a very big list of unicode chars, as well as compiling some existing lists
but yeah I went though every unicode char by hand lol
Nice, at least now I know I am not the only person who has a lot of free time
Hm, understandable
oh well energy drinks π can relate
I drank one day before yesterday and pretty much was awake all night
Too much free time
I've had 4 redbulls in my life and half of them were for that list lol
.bm some symbol stuff (letters and numbers) idk, just seems useful
drinks/caffine doesn't seem to affect me, like i have never felt like i dont want to sleep after drinking coffee
only 4? π
I think I should stop drinking everyday now
π
I haven't drank a single energy drink yet π
school tomorrow?
woah thats damn useful for unknown encodings
do asher's reactions look fake-like to me or what π
ye
sad
same thing
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
sleep, otherwise you will miss the bus to school
I drive tuktuk, I take him to school.
ouf
π
lmfao
Is the ppt on βdid wizard hit the mommyβ perhaps
English class 12π
It was I who abused aunt Jennifer
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Heh
f coz of u another dumb poem ;-;
I understood every single word
lip readerπ
lip kisser
Now I can't even kiss on lips bro
!ot or next ping to mods
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Another cool hecker boii, desktop environment or window manager
rly?
Let's move to ot, he being a dick
hello
What a dick
i dont want ban so calm down
I'm here
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
everyone please abide by our #rules and #code-of-conduct
that means staying on topic, not insulting one another by calling them dicks, etc.
last warning for everyone
I saw dpy has tons of regular updates since they restarted development
funny
that's what maintainence is...
I mean its a fair point
dpy was made because danny needed a discord lib, I'd assume
There tree crap sucks balls
wheel was invented y a human nit a cave
yeah but it does seem a lot more active compared to before they stopped right?
either get or fetch the channel object by ID and then send to it
hm yeah, well discord is rolling out updates pretty fast too, ps the library contains a huge amount of bugs, so π
Client.get|fetch_channel
make requests to the api easyyy
then what do you expect
"I want a car but I don't want it to have wheels"
everything on web works using requests
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
No lol
gRPC is now sad
Are you by any chance autistic
flying carπ
loool nova
:D
I uh, offtopic pretty fast
see
it was a shitpost
that i posted
and new convo begins
!ot dont make me do it π
I swear this chat becomes less useful every time I look
L
sparky laying baits
it's useful?
not anymore lol
In which cases would Guild.voice_client not be an instance of VoiceClient?
amen.
ikr, i was editing my config, i alt tabbed once, saw mina scolding them, the next second they do the same thing
If you want useful crap then go to discordpy or any specific help server, this place ain't it
ot-3-discord-bots
who cares, as long as voice_client is not None
I care because my linter won't shut up
abuse it physically
noqa
you're using pycord I assume?
No, dpy 2.0
ew
Most useful trick ever
!d discord.Guild.voice_client
imagine using pycord
Use it
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
ah, a proto
ya its VoiceProtocol not VoiceClient
ew
Misleading name
its dpy, its expected
I don't wanna sound harsh but if you're going to contribute literal empty messages instead of anything remotely on-topic please just don't.
When I want to use a method of VoiceClient I have to assert/isinstance prior otherwise my linter starts throwing gang signs. Any suggestions?
can you typehint it as a VoiceProtocol and then use the proto methods?
typing.cast(typ, val)```
Cast a value to a type.
This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally donβt check anything (we want this to be as fast as possible).
christ can we actually stay on the bloody topic not just send meaningless spam
it tells you to assert because voice_client could be a NoneType
!mute 431677941722906625 
:incoming_envelope: :ok_hand: applied mute to @grim oar until <t:1657478900:f> (59 minutes and 59 seconds).
poor nova
Nooo they were helping me π
wrong id i assume?
Can I use this as an annotation or something
you do uh
go dms
giving help with phrases like ffs and loser aren't in line with our code of conduct
please stop spamming.
my_thing = typing.cast(VoiceClient, extisting_object)
and that signals to the type checker that my_thing is a VoiceClient no matter what type it thinks it is
That happens everyday here
in fairness with the 'loser' comment that was clearly a friendly joke within the context this time, if that means anything
*clearly to us, not necessarily an outside view of the convo
public community means public moderation policy, so no, those comments won't fly here
Then let us work to raise the level of acceptable interactions here.
no
mhm whatever the rules say, can't oppose π
they do
being a mod/admin in such a big community
can you guys just stop shitposting at this point
Generally helping guide and maintain a community that, for the most part, is incredibly helpful to each other.
finish ur home work
you are an egg
here we go
here I go
imagine
if you specify the class with i think VoiceChannel.connect
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
!e
print("True"[-1],"g"*2)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
e gg
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
there's a channel for bot commands lol
while the name of the channel being discord-bots may confuse you into thinking it is a command channel, this is not #bot-commands
!tban 953394680073179207 1m repeat offender and history of not following our rules on 2 accounts.
:incoming_envelope: :ok_hand: applied ban to @white raft until <t:1660155104:f> (30 days and 23 hours).
@bot.event
async def on_message_delete(message, ctx):
embed = discord.Embed(title="Message Deleted", description=f"Message by {message.author.name} was deleted", color=0x00ff00)
await ctx.send(embed=embed)
TypeError: Client.event() missing 1 required positional argument: 'coro'
i dont understand whats wrong
@bot.event
async def on_message_delete(message):
embed = discord.Embed(title="Message Deleted", description=f"Message by {message.author.name} was deleted", color=0x00ff00)
await message.channel.send(embed=embed)
yes
gives the same error
How have you define bot?
Make sure you save and relaunch it.
bot = commands.Bot(command_prefix=';', intents=intents)
Looks like you forgot to instantiate Client
do you use @bot.event with () somewhere in your code
yes
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.messages = True
bot = commands.Bot(command_prefix=';', intents=intents)
@bot.event
async def on_ready():
print('Up and running:', bot.user.name)
@bot.event
async def on_message_delete(message):
embed = discord.Embed(title="Message Deleted", description=f"Message by {message.author.name} was deleted", color=0x00ff00)
await message.channel.send(embed=embed)
what exactly do i change
do you have another event
no below this is just commands
that's weird
definitely not
does anyone have an 'empty'/invisible' ascii character that I can put in my embed field value to make the code think somehtings there when there isn't somehting there
i still couldnt find a solution(and with the hardcoding i couldnt figure it out)
you put self as an argument
even though you're not in a class
oh wait i did
you don't use self outside of classes
should i just remove that?
yes
is there anyhting I need to wrap this in? Tried doing \U200b but got a unicode errorpy SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-5: truncated \UXXXXXXXX escape
u want an invis char ?
like this
β
yep
okay thanks
Okimii
the impl of slash
might be worth asking in their server not sure if pycord is commonly used here
alexdev
damm d.py's detrecting it and saying the embed field is missing content
Small u
thanks. also how would i go about making this create a private channel so only mods can see it?
it's linked on their docs
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a βsecretβ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
you see the overwrites parameter?
youre welcome
the overwrites parameter takes a dict, with a role as key and permissions as name
you might wanna have something like
\uU200b? I don't really work with unicode emojis
wait I have to go see some examples
ππΌ
Dear God how much do I need to spoonfeed
\u200b
how is that spoonfeeding
thank you
I'd prefer if you just chose to step back and not help as opposed to acting this way
No reason to cop an attitude
@slate swan this is an example
the key of the dict is the role, the name is a discord.PermissionsOverwrite instance
or a list of discord.PermissionsOverwrite instances
code pls
they are like a pop up menu allowing to input something then submit it
ah
lmk if wrong but would this work
got it sorted π altho I think I abused TheMethGuy's generosity and integrity. For a ida of what was being a problempy embed.add_field(name=article.label, value=article.description if article.description else " ",) # Invisable char in the string kept telling me the field value was required, my fix thanks to TheMethGuy was py embed.add_field(name=article.label, value=article.description if article.description else "\u200b",) # Uising unicode emoji instead of invisable char
π
no cuz member is undefined
I assume it's meant to be ctx.author
you also have two unnecessary wait_fors after await msg.add_reaction()
it's also str(reaction.emoji), not str(reaction) in your check
ah
!d discord.ext.commands.Bot.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**...
and also how would i go about once the bot makes the channel it gives a closing option by pressing button? (if it doesnt mean using a db)
will do
a closing option where?
Cool ex. I can do lots of thing with it
pass_context Gross
So once when it creates the Ticket channel In that channel it will give an option to close the channel
kinda like what the ticket bot has?
if i made sense there
how to check if a channel has nsfw on
nvm
hi
If the channel is marked as βnot safe for workβ or βage restrictedβ.
is ctx.content a thing?
how do i get the whole phrase sent by user in bot command
and store it
its ctx.message.content
how do i make my bot online 24/7?
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is βsyntheticβ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
Oohhh
run the file 24/7
i can host on the bot somehow and somewhere online or something?
Yes, buy a VPS
You will still be running the file 24/7, but on someone else's computer
how much vps?
Depends on where you get it from
germany
ah okay
Err my bot is refusing to respond to commands
is there anything better and faster around the bot 24/7 online?
I have no on_message event override in my subclass, message content intent is enabled and my command cogs have loaded
What's up now?
Sorry? I'm not understanding
When I do override on_message to print and THEN process commands it prints out the message just fine
But the commands aren't processing
If that's true, then your commands should work. Logically then, that's not true
a hoster or something where i can install the bot or something
Yeah, that's why I said buy a VPS
and how can i install the bot on the vps?
Easiest way would be to upload your bot's code to github, then git clone <url> on the VPS after SSHing in, cd <dir> into the cloned directory, python3 <filename>.py
Okay thx
Preferably also set up CI/CD so you can automatically deploy pushed changes to the production server
my bot is having problems with the install command, do you have a better command to install python from git?
What install command?
for my py bot
Are you trying to install python?
the install command dont work
I'm not sure what install command you're talking about
yes
Ah, you can install it from python.org if you're on windows
Most linux distributions will have it in their respective package managers
a link from github to install python
You can find the downloads here: https://www.python.org/downloads/
the install command from github with powershell i mean
Oh, you want to compile from source?
yes
Clone this repo: https://github.com/python/cpython
Is there a max amount on SelectOptions?
Then follow the "Build instructions" in the README
25?
25, Yes
sheees
π
If you want, I can package the entire source code into a zip file just to prove it
Of course omitting the token and venv
I don't mean to be brash, but most of the time when there's an issue like this, and people say they've tried absolutely everything and they're 100% sure nothing else is wrong but it's still not working, it's something small they missed
Hm
Very well then
intents: discord.Intents = discord.Intents.default()
intents.message_content = True
"""Gateway intents to use when connecting to Discord."""
class Versare(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=self.get_pre, intents=config.intents)
self.pool: asyncpg.pool.Pool = None
async def get_context(self, message: discord.Message, *, cls: Optional[type] = None) -> commands.Context:
return await super().get_context(message, cls=cls or VersareContext)
async def get_pre(self, message: discord.Message) -> list[str]:
prefix: str = self.prefixes.get(message.guild.id, config.PREFIX)
return commands.when_mentioned_or(prefix)(self, message)
async def load_extensions(self, directory: str) -> None:
for file in Path(directory).rglob("*.py"):
if "__" not in file.name: # ignore __init__.py
await self.load_extension(f"{directory}.{file.stem}")
await self.load_extension("jishaku")
async def setup_hook(self) -> None:
"""Performs setup tasks for the bot. Initialises dataabase connection, loads extensions, etc."""
self.pool = await asyncpg.create_pool(config.POSTGRES_DSN_FORMAT.format(**config.private.POSTGRES_CONFIG))
async with self.pool.acquire() as conn:
async with conn.transaction():
with open("db/schema.sql") as f:
await conn.execute(f.read())
self.prefixes: dict[int, str] = dict(await conn.fetch("SELECT id, prefix FROM guilds"))
await self.load_extensions("cogs")
async def on_ready(self) -> None:
print(
"Versare is ready!\n"
f"Username: {self.user}\n"
f"User ID: {self.user.id}"
)
if ctx.message.content == any(word in ctx.message.content for word in Snsfw) and ctx.channel.nsfw:
await ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", delete_after=1)
async with ctx.typing():
for j in search(query, tld="co.in", num=1, stop=1, pause=2):
await ctx.send(f"\n {j}")
await ctx.send("Have any more questions?,feel free to ask again!", delete_after=10)β
unindenation at async with ctx.typing():
(cant cipy pasteerror on my phone)
help
@slate swan
what am i doing wrong
Your indentation is incorrect, judging from what you pasted. async with ctx.typeing():
how to solve it??
Align the indentation with the line above and below it.
if ctx.message.content == any(word in ctx.message.content for word in Snsfw)
that's wrong
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
you see it returns True or False
still not workingvg
ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", delete_after=1)
async with ctx.typing():
for j in search(query, tld="co.in", num=1, stop=
if ctx.message.content == any(word in ctx.message.content for word in Snsfw) and ctx.channel.nsfw:
await ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!", delete_after=1)
async with ctx.typing():
for j in search(query, tld="co.in", num=1, stop=1, pause=2):
await ctx.send(f"\n {j}")
await ctx.send
its aligned
def mycheck() -> "Check?": # type: ignore # what's the return type here?
async def predicate(ctx: commands.Context) -> bool:
return True
return commands.check(predicate)
...
@commands.command()
@mycheck()
async def mycmd(self, ctx):
await ctx.send("oi")
``` What's the appropriate return type for commands.checks?#
@wary shadow
its alignedand still doesn't work
Is this paste you are providing incorrect then?
is that discord light mode
- Don't use that if comparison, remove
ctx.message.content == - Instead of
ctx.channel.send, just doctx.send - Do not use Replit. Whatever you do
Okay, then the paste is incorrect. That happens, unfortunately. Adds confusion. :(
my life is sad so i use replit
if ctx.message.content == any(word in ctx.message.content for word in Snsfw)...
any(word in ctx.message.content for word in Snsfw)
Just do that
Else it's str == bool
Oh
await ctx.channel.send(f"Looking for results related to your question {ctx.author.mention}!",
delete_after=1)
for j in search(query, tld="co.in", num=1, stop=1, pause=2):
await ctx.send(f"\n {j}")
await ctx.send("Have any more questions?,feel free to ask again!", delete_after=10)β
i removed typing
wtf how it copy pasted likethat
googlee
It's blocking :(
blocking what
blocking async
Are you, by chance, mixing spaces and tabs? You mentioned replit, I don't know if it allows tabs and spaces. 
Could someone provide some info on TextInput it keeps giving me invalid form body ```py
discord.app_commands.errors.CommandInvokeError: Command 'cheese' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.2.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
im on mobile
bruh dm me TextInputs are modals only.
I.. don't like that.
If I run a command that has a long asynchronous task will the bot accept other commands while that task runs or does it queue the command for after the asynchronous one completes
If it's 100% asynchronous and not blocking, you can run other commands
HI, my bot works fine but I have him on multiple server and the on_member_update
is getting called once x server.
How can I handle it?
BOT
import discord
from discord.ext import commands, tasks
from datetime import datetime
import sqlite3
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', case_insensitive=True, intents=intents)
conn = sqlite3.connect('database.db')
c = conn.cursor()
@bot.event
async def on_ready():
print("-------------------------------")
print(f"Logged in as {bot.user}")
print(f"With id: {bot.user.id}")
print("-------------------------------")
@bot.event
async def on_member_update(before: discord.Member, after: discord.Member):
if after.status != before.status or after.activity != before.activity:
print(str(before.display_name) + " was " + str(before.status) + " and is now " + str(after.status))
v_user_id = after.id
v_timestamp = datetime.now().strftime("%d-%m-%Y %H:%M:%S")
v_username = str(after)
v_status = str(after.status)
v_activity = str(after.activity)
c.execute("INSERT INTO data(user_id, timestamp, username, status, activity) VALUES(?, ?, ?, ?, ?)",(
v_user_id, v_timestamp, v_username, v_status, v_activity
))
conn.commit()
return
file1 = open('token.txt', 'r')
TOKEN = file1.readline()
bot.run(TOKEN)
How do you want to handle it? What outcome do you want?
how would i ensure it dosent block other commands and allows the bot to continue its heartbeat to discord
!env "Ahh please use env man. "
Python Environments
The main purpose of Python virtual environments is to create an isolated environment for Python projects. This means that each project can have its own dependencies, such as third party packages installed using pip, regardless of what dependencies every other project has.
To see the current environment in use by Python, you can run:
>>> import sys
>>> print(sys.executable)
/usr/bin/python3
To see the environment in use by pip, you can do pip debug (pip3 debug for Linux/macOS). The 3rd line of the output will contain the path in use e.g. sys.executable: /usr/bin/python3.
If Python's sys.executable doesn't match pip's, then they are currently using different environments! This may cause Python to raise a ModuleNotFoundError when you try to use a package you just installed with pip, as it was installed to a different environment.
Why use a virtual environment?
β’ Resolve dependency issues by allowing the use of different versions of a package for different projects. For example, you could use Package A v2.7 for Project X and Package A v1.3 for Project Y.
β’ Make your project self-contained and reproducible by capturing all package dependencies in a requirements file. Try running pip freeze to see what you currently have installed!
β’ Keep your global site-packages/ directory tidy by removing the need to install packages system-wide which you might only need for one project.
Further reading:
β’ Python Virtual Environments: A Primer
β’ pyenv: Simple Python Version Management
as if the bot would be just on one big server
(just one call at a time per user)
You kind of need to know that yourself, e.g your connectors for all databases are asynchronous, you're using aiohttp instead of requests, etc
Basically anything that's relatively long running (I/O mostly, non-CPU bound tasks) are asynchronous
That's going to be a bit trickier. You aren't going to have the guarantee that each server's event fires at the same time so filtering by time isn't super viable.
how would i keep the video encoder i use to stop halting the heartbeat and other commands?
See if there's an asynchronous version of the video encoder
The problem that I see is just the the time that I save just goes down to sec
If not, you can try running it inside an executor
or if you want to be extra, set up a seperate media processing server, and send requests via aiohttp
Or did I not understand your solution right
I don't have a solution yet. It's a tricky one to me.
I would store the guildId with the event and be done with it. Keep the duplicates. Sort it out in reporting afterward.
Can someone help me set up buttons for my suggestion prompt because I'm having a good bit of trouble with it giving me an error and I think it has to do with my python version or something but I'm not sure
import discord
from discord import ActionRow, ButtonStyle, app_commands, ui
from discord.ui import Button
from discord.ext import commands, discord
from datetime import datetime
I think it has to do with ActionRow and ButtonStyle?
and Button
is there a code example you reccomend for that?
dont import discord from instide discord.ext
Ty!
@stiff fern instead use
import discord
from discord import ActionRow, ButtonStyle, app_commands, ui
from discord.ui import Button
from discord.ext import commands
from datetime import datetime
OK, for this I would need to acces the last database row right?
like if all colums match and the guild_id is not the same drop
or what had you in mind?
accept = Button(
style=ButtonStyle.green,
custom_id="success",
label="Accept")
reject = Button(
style=ButtonStyle.red,
custom_id="danager",
label="Reject")
action_row = ActionRow(component=[accept, reject]) # <-- here
suggestion_response.set_author(name=interaction.user, icon_url=interaction.user.avatar)
await interaction.response.send_message(embed=suggestion_response, ephemeral=True)
suggestion_message = await review_channel.send(embed=suggestion_embed, Component=action_row)
@app_commands.Bot.component('success')
async def accepted(self, interaction: discord.Interaction):
print('Works!')
Do you know if I'm doing this right? Because it says Component is an unexpected keyword argument
hey
i downloaded all discord libraries and pipenv and i cant import discord
i did it a lot of times, but this time i dont know why i cant import it
i dont know about that sorry i use disnake which has everything that extra thing imports
Oh I see no worries
im not sure of any fork of discord.py that makes you write message components like that
Discordpy documentation makes it kinda hard with all these extra libraries π΅βπ«
thats why i use disnake
its literally a fork of discord py that has extra stuff in it.
It looks like discord components and dpy 2.0 had ***
Yea but at this point I feel trying to learn something new would just make this take 100x longer
I think I just organized it wrong
imma try and do it this way
I recommend using an up to date library.
I mean this should be upto date no?
psssttt its easier lmao. you can just learn the different way that they use the components. its built in to disnake
here's a quick example of writing some buttons to send alongside a message (dpy 2.0 and most forks have this): ```py
class MyView(discord.ui.View):
@discord.ui.button(label='Hello')
async def on_hello(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('hello there!')
@discord.ui.button(label='Goodbye')
async def say_goodbye(self, interaction, button):
await interaction.response.send_message(f'Goodbye, {interaction.user}!')
await ctx.send('tell me something', view=MyView())``` further examples of views are in the github: https://github.com/Rapptz/discord.py/tree/master/examples/views
and view documentation: https://discordpy.readthedocs.io/en/latest/interactions/api.html#bot-ui-kit
afaik you should never need to assemble the action rows and components yourself
oh thank you
hey i have a problem, i have imported all the discord libraries and when i import discord, discord.ext or discord.py it shows a problem with missing imports
can you show the traceback you got when you tried writing from discord.ext import commands?
Import "discord.ext" could not be resolved Pylance(reportMissingImports)
from discord.ext import commands
yea thats what i have
Β―_(γ)_/Β―
how did you install discord.py?
and what does vscode say about the python version in the bottom right corner
did you use pip to install discord.py? @forest oyster
what os are u using cause when i used to use macOS for discord.py it wouldnt work @forest oyster
pip install discord, pipenv install discord, pip install -U discord.py
im using windows 11
nooooo
uninstall it using all three
god only install it once
pipenv manages the virtual environment for you, so you might have 1.7.3 installed on both the global python and autogenerated virtual environment
lol i use pycharm so i use its pip
^
ye pycharm's integrated terminal activates your virtual environment automatically
the 'disnake' way was forked off discord.py'. I woul d just recommend using the most popular being discord.py 2.0
eh u do u. also love ur new pfp
thx!
i uninstalled everyone and only installed pipenv install discord but its the same
please just install it in pip
anyways back to dnd i go
So I can see how they make the buttons here but in this example they place it in a class and then call that class with a message, how would I activate the buttons without having to make it into a class?
Would I put it into a actionrow again
no?
Or does it have to be a class
you could do view=self
o
but ur indentition is messed up
can you click the python version displayed in the bottom right corner of vs code and show what vscode tells you? the dialog should look something like this
How?
ur callback should be inside the button functions not outside
this will never be called
3.10.5
Sorry I may sound a bit dumb, are you saying the button function should go behind the view instead of in front of it?
Because if I put it inside the function how would I get called if that's whats calling it in the first place
Or I might just be completely misunderstanding
the
@discord.ui.button
``` decorator *wraps* a function and the callback of the function becomes the button's callback
im not understanding
So you press the button and whatever is inside that function runs yes
yes
Right, so this is what I want the buttons to be attached to but it's not what happens when the button is pressed
so you want a message to be sent with this view?
can you show the full line that vscode highlighted? and also wherever you typed pipenv install discord.py, can you share where pipenv's virtual environment is located by typing pipenv --venv
(sidenote: discord is a mirror of the actual package discord.py but since you already installed discord, you'd stick with that)
Yes I want the message to be sent w/ both buttons
I have the rest of the code of what happens depending on what button is pressed I just didn't put it together yet because I wanted to get this system working first
the view (the class) contains both buttons
you will create an instance of ur class and then send it
but that isnt done inside the class
its done outside
like you could have a sample command like
from xyz import Confirm
@bot.command(name="hello")
async def hello(ctx: commands.Context):
await ctx.send('hi', view=Confirm())
C:\censored\censored\ .virtualenvs\YBN_bot_developing-27A7H0f1
Wouldnt i be able to use the custom_id= to label the buttons and then do
view=whatever the name of the id is
no
damn
view needs to be a subclass of View/instance
you can do
@discord.ui.button(custom_id=...)
you can set custom ids in here
Right but then whats the point of having a custom id
is that the one vs code told you, or the one that pipenv --venv gave? you need to make sure vs code has selected the virtual environment that pipenv created so it knows where discord.py is installed
if you wanted to override some behavior (not recommended) and for persisitent views
o
whihc still work after the bot has been reset/restarted
Okay so thats some other thing Im not messing w/ atm
the pipenv --venv one
So then whats the difference between component= and view=
Would they both work for buttons?
component is from discord components a third party library which shouldnt be used with discord.py
discord.py is much better to use
do you see a python interpreter listed in the popup dialog with the same "YBN_bot_developing" name when you click the python version in vs code? if so, click that and try running your script in vs code again
Oh alright
there really isnt a need to use third party libs rn because all major new features are supported
the effects of monkey patching dpy libs are still being felt to this day
yea i see it, but i can run it beucase the discord module is not downloaded acording to the terminal
yes π
this is the channel i like helping in most but with all the libs/third party things its very challenging π
what did the terminal say, ModuleNotFoundError: No module named 'discord'?
yeap, exactly this
uhhhhhhh can you run pipenv graph to show what packages are installed
its hard to tell whats going on without seeing the entire terminal's output
yea wait a second
Any integer between -2^53 and 2^53
Hey @forest oyster!
It looks like you tried to attach file type(s) that we do not allow (.bmp). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
guess vs code is just misconfigured then
well your code should run if you type pipenv run python main.py, or whatever you named your script
sad there isnt a big int or long optjon
ah, 2^53 is the mantissa for 64-bit floats used by javascript's number type
@ionic turtle another question but how would I update the button to be greyed out when someone presses it? I realize self.stop() makes it where it'll basically not respond when you press it but isn't there a way to make it where you can't press it at all or something cleaner?
you would set the button to disabled
and then edit the message
Yes, but keep in mind that only sets the view classes' value property to False. It doesn't actually disable it on discord
You'll have to re-send the view for it to take effect
if you wanted to disable all of them use like a loop
@discord.ui.button
async def xyz_button(
self,
interaction: discord.Interaction,
button: discord.ui.Button
):
...
for item in self.children:
item.disabled = True
await interaction.edit_original_message(view=self)
Oh so the loop is always at the end of the script
you could do at begining it doesnt matter
Oh alright
the confirm.py example you saw earlier uses self.value as an easy way for the command to tell whether the user clicked confirm or cancel, but its merely a custom attribute that the developer of that example chose to use; you could write any attribute that doesnt conflict with whatever's documented in View like self.user_id (say for an interaction_check() to make sure the view is only usable by one person) or self.bot (maybe to access an attribute in your bot, like a database)
So what does self.stop() do
it makes your bot forget that view ever existed
Oh alright
if someone clicks on it afterwards, the bot receives an interaction pointing to a message+custom_id that it isn't aware of and silently ignores it
So here's a question, edit_original_message edits the interaction that's inside the button function but how would I edit the actual original message which would be the suggestion embed
Because you can do self.children I dont know if theres a self.Parent that works for that too lol
original_message is the message that the view is attached to
theres documentation
no need to guess attributes
and no theres no self.parent because self is the 'parent' of the children items
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
It should be the message the view is attached to but it's giving me an error?
i shall look
what error
try
message = await interaction.original_message()
await message.edit(...)
note this is an http request
not necessarily, original_message() is only available after you respond to an interaction and the message it refers to depends on how you responded to the interaction
Still errors and I think it's because I moved the interaction within the actual button press function above the edit and it's trying to sync the original message with that message
send_message()makes it refer to your new messageedit_message()anddefer()makes it refer toInteraction.message
with send_message(..., ephemeral=True), you can even edit it afterwards using original_message()
@discord.ui.button(label="Reject", emoji="", style=ButtonStyle.red)
async def reject(self, interaction: discord.Interaction, button: discord.ui.Button):
for item in self.children:
item.disabled = True
message = await interaction.original_message()
await message.edit(view=self)
await interaction.response.send_message('Cancelling', ephemeral=True)
suggestion_response.set_author(name=interaction.user, icon_url=interaction.user.avatar)
await interaction.response.send_message(embed=suggestion_response, ephemeral=True)
suggestion_message = await review_channel.send(embed=suggestion_embed, view=Buttons())
Yes its a new interaction
And because it was using that one I moved it up so it wouldn't use it and now it basically can't find anything to edit lol
if you want to edit the message as your response, you'd use interaction.response.edit_message()
if you want to edit the message before/after your response, you'd use interaction.message.edit()
Oooh
Oh damn I thought response was just something you had to put to use edit_message
damn - that makes sense too
Haha it works now
Is there a way to do the equivalent of self.self lol
In terms of scope
For example I need access to this Answer_one input
From the modal inside the class of the button functions
Normally if they were outside of that class I could do self.answer_one
But since its basically another scope in, I can't do that so I was wondering if there's some other method
its unpythonic to nest a class in a method, but whether you put it outside or not, you can define a custom init method for your Buttons class with a parameter to store answer_one
I only did it because it was the only way I could figure out to actually get the buttons to work π¬
for example: ```py
class SuggestionView(discord.ui.View):
def init(self, suggestion_text, *args, **kwargs):
super().init(*args, **kwargs)
self.suggestion_text = suggestion_text
@discord.ui.button(...)
async def accept(self, interaction, button):
# use self.suggestion_text here```
Oh okay I see
although are you sure you need it? im guessing the suggestion embed you'll be sending with Buttons will already have the answer in its description
in which case you can access the existing embed with interaction.message.embeds[0] and simply change the parts you're updating, like the title/color, then edit the message with the embed passed back
I didnt even know you could do that ty
also note that dpy will overwrite the answer_one attribute with a string when on_submit is called, so you have to access the label through the class object itself, i.e. suggestion_modal.answer_one.label (whatever the user typed would be in self.answer_one)
Ty
Do you know how I would get the user who interacted with the button
interaction.user?
ye

So if this returns the embed how would I get the attributes of that embed ?
interaction.message.embeds[0].label
didn't work
put it in a variable for easier use, then whatever parameters you can pass to discord.Embed() can also be set with =
embed = interaction.message.embeds[0]
embed.label
embed = <the existing message embed>
embed.title = 'Suggestion Denied'
embed.set_author(...)```
nvmlol
class Buttons(discord.ui.View):
def __init__(self, answer_one, *args, **kwargs):
super().__init__(*args, **kwargs)
self.answer_one = answer_one
Tried putting self and answer_one but it still returns the same error?
well you've made a new required parameter for the Buttons class, so it has to be given when you construct it in Buttons()
I've tried addingn self.answer_one to the class but that also gave me an error
Unless thats not what you meant
OH - got it thank ya
The channel's so dead at this time 
I mean I can ask a million questions but I try not to spam the channel for stuff I can figure out in due time lol
Like rn I dont understand why the top for loop doesn't work but the bottom one does
Bro why split when u can do interaction.user.name
Wdym by doesn't work
Tell more briefly
Any errror
So I have 2 buttons,
If I press the Reject button (The bottom one in the example), it'll properly disable both buttons so you can't interact with either
If I press the accept button (The top one) it still lets me press both buttons and doesn't disable them
Sry gtg school vehicle camed
no worries lol
Show full code for top one
from the decorator
I realized I was getting an error because the response was trying to respond to itself multiple times or something like that and now I'm trying to write it the same way the reject code is written because ofc that one works but its saying I need to define the variable even though I didnt do it for the rejection one but yeah Ill send it even tho it may be long
@discord.ui.button(label="Accept", style=ButtonStyle.green)
async def accept(self, interaction: discord.Interaction, button: discord.ui.Button):
user_name = str(interaction.user.name)
# Embed for staff channel
suggestion_embed = discord.Embed(
title='Suggestion Accepted',
description=f'**{self.answer_one.label}**\n{self.answer_one}',
timestamp=datetime.now(),
color=0x49ba8b # Green
)
suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
suggestion_embed.set_footer(text=f'Accepted by {user_name[0]}')
# Embed for suggestion channel
public_suggestion_embed = discord.Embed(
title="New Suggestion",
description=f'**{self.answer_one.label}**\n{self.answer_one}',
timestamp=datetime.now(),
color=0x3f6782 # Default
)
public_suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
public_suggestion_embed.set_footer(text=f'Accepted by {user_name[0]}')
# Updating suggestion in staff channel
await suggestion_message.edit(embed=suggestion_embed)
# Getting suggestion channel
suggestion_channel = interaction.guild.get_channel(986755419894579261) or await interaction.guild.fetch_channel(986755419894579261)
suggestion_message = await suggestion_channel.send(embed=public_suggestion_embed)
# Adding UpVote/DownVote reactions
await suggestion_message.add_reaction('')
await suggestion_message.add_reaction('')
for item in self.children:
item.disabled = True
await interaction.response.edit_message(view=self)
self.stop()
you're doing a lot... like a lot a lot in your callback try doing
await interaction.reponse.defer()
``` in the begining of ur code
Are you not suppose to everything in the callback?
and replace the
await interaction.response.edit_message(...)
```with
```py
await interaction.edit_original_message(...)
no you just have to defer
Oh alright
what was the error you got when you clicked the accept button?
i think the adding reactions is adding time and may eventually exceed 3 seconds
but yeah, error pls ^^^
yeah id agree with that too
W/ defer it just says failed to respond but it doesn't give me an error in the console
Something along the lines of This response has already been responded to
oh do
response.defer(thinking=False)
ohh
hmm your screenshot doesnt seem to show it was misspelled
It works now thank you :)
My screenshot didnt have the defer in it
does it work with the defer?
It does
thinking is false by default so you dont need to include the argument
π
i would just move the edit_message to before the send() and add_reaction(), and also update the embed through the interaction
although this way would need a few permission checks to make sure the bot can actually send messages/reactions before disabling the buttons
So what would be a better way of doing this on an optimization standpoint
Because it does take a solid second for the buttons to get greyed out and if I spam it then multiple prompts send which isnt a issue now but I'm just planning on if I add more if it's going to take longer each time what the proper way is
id go with the approach i described, i.e. check permissions first, then grey out the buttons + update the embed and do whatever afterwards
unless you really want it to be robust, then you can further reduce what your button must do so it stays under the 3 second limit, e.g. only sending the suggestion message and responding afterwards
that way you only disable the buttons when you know that message was sent, and if your bot fails to add the reactions you can send a followup warning so at least the moderators are able to add it at a later time
oh and the user can't click before the bot responds
i think its pretty easy to over-engineer this
So if I do this how would I do the rest of the actions outside of the button press function
Would I just call another class/function within that class
nah it can still be in the same callback, im just saying the response to edit the view/embed would happen first and then sending/reacting happens after
Oh that makes sense
It gave me this error when I moved
for item in self.children:
item.disabled = True
await interaction.edit_original_message(view=self)
self.stop()
to the front
with this approach you just need edit_message(), no defer() or edit_original_message()
also edit_message can take an embed= parameter
Oh alright
i recommend you update the embed in the interaction so you aren't double editing the message
Wouldnt I have to edit it after disabling it so it shows on discord?
Or else wouldn't it still be delayed
π
Do you know how I would make the bot only reply to direct replies to its message
The things I'm finding are if someone sends a message regardless of they replied to it or not
!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.
check if reference.resolved is available and was authored by your bot
ty

It doesn't DM on Join
These are the Imports plus the member intent being enabled
Here's what was written in the console
Ping me if you guys can help
Also, any resources you guys can give me to fix this also helps. 
I'll just come back again for questions if needed
Or add intents.message_content = True
This one doesn't have an attribute
Also, I did this. Still didn't work
Do u enable intens from discord developer portal?
Could it have something to do with the bot.listen decorator?
Last I used it, it also didn't work
@bot.listen()
async def on_message(message: Message) -> None:
if "badword" in message.content:
await message.delete()
Last I used the listen decorator, this one also didn't work -- Also no errors being said in the console when ran
Try @bot.event
Wait, are you using disnake and discord.py?
that wouldnt make a difference?
I think listen is for cogs
Disnake
your error is related to the message content intent lmao
He add intens.message_content and got this error
what about dev portal?
He alr enabled intents
Lemme check
and your bot uses disnake :))
from disnake import CommandInteraction, Message
from disnake.ext.commands import Bot
from discord.ext import commands
from discord import Intents
import os
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
bot = Bot()
These?
yes just remove bot = Bot() and the import and replace discord with disnake
and your problem should be solved
hey how can i get a users discord tag, for example i want to use something like member.display_name but with the numbers at the end
further ex
i want SnowZillin#4335
just do kill 1 in your terminal
just make the member obj a string
the str dunder of the class should return the whole tag
Yes. Finally worked
Thx alot!!!
youre welcome guys ;))
Also, guys. One more thing
Flask is what's often used to make bots online, right?
Can u guys, send me a resources about it or smth
I'd like to learn how it works in keeping bots alive
not quite
vps
people just use flask and keep alive to keep the replit container running
use vps instead of replit
use a vps and consider moving to this thread for further help on the topic #965291480992321536
I'll probably just watch And read more articles later. For now, I'll try Testing some stuff out. Might be too much to handle for me rn
u use replit?
Yeah. 
Nah. What's a VPS?
Still just a month-ish in on coding so Still not very familiar with most terms
Ah. Nah. I don't really ask my parents for stuff. I doubt they'd buy it anywyas
Well, for now, I'll probably just get used to how to make commands. And eventually when I think I have enough understanding, will learn how to make it alive
a virtual private server*
dont ping me 4 dat lol
the definition of the term is a Virtual Private Server so atleast say what the term means πΏ
full form* not definition, but sure
#965291480992321536 would be a more appropriate channel for this
im not discussing further
im pretty sure changing words that aim for the same point doesnt really matter but ok
you do you
Ideas on what this means?
I'm not sure what lines its referring too because I only have 200 so I don't know what portion of code to share
you could be deleting/editing/fetching a message which doesn't exist
ok ty
the exception mentions edit_message so presumably it's that
ty!
@vocal snow do you have an idea on how I can reference a difference interaction within a separate interaction? Thats where the error is coming from
Rename the parameters so they are not both named interaction
o
tbh thats how I saw it written even where so I didnt even think to do that
you can reference them globally though?
hey
Hey guys!
https://github.com/code-chaser/dex :- a discord bot created by me π;
It's my first try at python - all kinds of reviews are most welcome!
Most importantly, I'd be really grateful to anyone doing code review;
Thanks in advance! π
This is DEX, a multi-purpose discord music bot made using discord.py. - GitHub - code-chaser/dex: This is DEX, a multi-purpose discord music bot made using discord.py.
Thats cool!
v = cast(Voice, self.guild.voice_client)
if v is None:
raise NoVoiceException
return v
``` is this cursed?
Type casting to Voice so that reveal_type(v) is ALWAYS Voice not Voice | None then checking if it is None, indeed cursed
It makes more sense to cast after checking if itβs None
ok ty!
Question, how am I suppose to reference the value of label? Do I need to to tostring(label) or something?
Because thats what it comes out like
cast returns the object that is so convenient βΊοΈ
From what I have already noticed
- Very cool design
In your bot class there are some things you could improve
- Never seen anyone using UPPER_SNAKE_CASE for attributes (I mean DATABASE_CONNECTION), it's typically used for classvars
- I wouldn't recommend storing links as classvars of bot class. It's better to create a module called
constantsand put them all to there or even use some other system - Doing SQL queries like this
con.execute('INSERT INTO tbl (id, name, surname) VALUES (50, \'man\', \'sus\')')```
is a bad idea. SQL insertions exist (or whatever they are called)
```py
con.execute('INSERT INTO tbl (id, name, surname) VALUES ($1, $2, $3)', 50, 'man', 'sus')```
4. There's a better way of making an error handler I typically use to avoid all those if-elif-elif-elif-... constructions. You can check it out here https://github.com/Exenifix/AIAS/blob/master/utils/errors.py (and yeah I do have small mistake in members getting)
button.label
Ty
And you could also setup some better logging
!pypi exencolorlogs you may use ready solution or create something by yourself
what for did I link personal purpose package
Hey guys i have a problem with discord.py i have made a custom prefix (from tutorial) and i will like to make when the member mention the bot it will send the prefix and im using modules so here is my main.py code
# Prefix
def get_prefix(client, message):
with open("prefix.json", "r") as f:
prefixes =json.load(f)
return prefixes[str(message.guild.id)]
# Prefix, Owner, Disable default help command
client = commands.Bot(command_prefix = get_prefix, owner_id = 468194427903410176, help_command=None)
# When Roumy is online send to console `Roumy is online` and set status `Listenis to ?help`
@client.event
async def on_ready():
await client.change_presence(activity=discord.Activity(
type=discord.ActivityType.listening, name="@Roumy", help_command=None))
print("Roumy Is Online!!")
# Add prefix when bot join a server
@client.event
async def on_guild_join(guild):
with open("prefix.json", "r") as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = ","
with open("prefix.json", "w") as f:
json.dump(prefixes, f, indent = 4)
# Remove prefix when bot leave a server
@client.event
async def on_guild_remove(guild):
with open("prefix.json", "r") as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open("prefix.json", "w") as f:
json.dump(prefixes, f, indent = 4)
# Set Prefix command
@client.command()
@commands.is_owner()
async def prefix(ctx, prefix):
with open("prefix.json", "r") as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open("prefix.json", "w") as f:
json.dump(prefixes, f, indent = 4)
await ctx.reply(f"Prefix change to: {prefix}")
@prefix.error
async def prefix_error(ctx, error):
if isinstance(error, commands.CheckFailure):
prefixError = discord.Embed(
title = "Permission Denied",
description = "Missing `Administrator` permission",
colour = 0xeeffee)
await ctx.reply(embed = prefixError)
@prefix.error
async def prefix_error(ctx, error):
if isinstance(error, commands. MissingRequiredArgument):
prefixError2 = discord.Embed(
title = "Error",
description = "Please specify the prefix - `prefix <prefix>`",
colour = 0xeeffee)
await ctx.reply(embed = prefixError2)
Sorry if i have done something whorg im new to discord.py
Btw i have set the set prefix command for owner only because i already add it to my main bot
Here is my mantion command:
import discord
from discord.ext import commands
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if message.content.startswith("@outer quarry"):
mention = discord.Embed(
title = "The prefix is `,help`",
colour = 0xeeffee)
await message.channel.send(embed = mention)
def setup(client):
client.add_cog(Moderation(client))
Json database cring
how would i set a variable to a message if somebody inputs a certain starter phrase
for example
@client.command(
async def setname(message):
new = message.context.replace('!setname ','')
which library is this?
what are you trying do?
when you define a command like:
@command()
async def command_name(ctx: commands.Context) -> None:
...
to use this command you would type !command_name
the first parameter of this command is ctx which is an instance of commands.Context
*discord.ext.commands.Context
oops
how do i get textchannel name by command
You mean get the text channel?
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
Whatβs the best way to handle mutes, so if I update my bot the mute timer tasks arenβt lost
just use timeouts. or a database
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.
@bot.event
async def on_ready():
print('Running:', bot.user)
await bot.change_presence(status = discord.Status.online, activity=discord.Game(name='Cyberpunk2077'))
bot.remove_command('help')
commands are loaded before the on_ready event, so you need to remove it outside
oh
or just do
bot = commands.Bot(..., help_command=None)
this works, thank you
also, dont change you status in on_ready
!d discord.ext.commands.Bot use the status and activity kwarg in this
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
both of those run the bot when i try the command >help it doesnt send anything
i kept it there incase i want to change it later on
but ill do this thanks
even if you want to change later, on_ready wont be helpful
https://gist.github.com/Okimii/0b6e5dcfcfb895ef613ac59a4ecc096a here's a nice gist about changing status
show your help command
@bot.command()
async def help(ctx):
embed = discord.Embed(title="Help", description="Commands", color=0x1abc9c)
embed.add_field(name=">help", value="Shows this message", inline=False)
embed.add_field(name=">ping", value="Shows the bot's ping", inline=False)
embed.add_field(name=">say", value="Makes the bot say something", inline=False)
embed.add_field(name=">tad", value="Terry A. Davis", inline=False)
embed.add_field(name=">whois", value="Shows the user's info", inline=False)
embed.add_field(name=">ip", value="Gives information about any ip", inline=False)
embed.add_field(name="Features", value="Logs deleted and edited messages in [#995965561248940092](/guild/267624335836053506/channel/995965561248940092/)/n Sends a funny when 'troll' or 'ripwin' is mentioned'/n Deletes swear words", inline=False)
await ctx.send(embed=embed)```
what library?
π my pc is not starting
π¨ use this and try
the startup cable that connects with main switch is losse
oh god
I need to tight it ;-;

why dont people subclass π
import discord, requests
from discord.ext import commands
Nitro π
ash nitro flex
cause not everyone is you ash
what ;-;
this is my second day using the discord module
i barely understand stuff
I don't even make a help command π
ah well
smh
there are 4 packages using the discord namespace, which one are you using and what's the version
slash command = free help cmd
just tell your users to pull up the slash command menu
discord, py-cord, nextcord, enhanced-dpy
all of them use discord namespace
nextcord allows both^
nitro π
smh
Name: discord
Version: 1.7.3
Summary: A mirror package for discord.py. Please install that instead.
Home-page: https://github.com/Rapptz/discord.py
Author: Rapptz
Author-email:
License: UNKNOWN
Location: c:\users\aymaa\appdata\local\programs\python\python310\lib\site-packages
Requires: discord.py
Required-by:
this?
ash buy me nitro pls π π
yeah its fine then
they stopped when discord.py continued with development kek
i liked their codebase tho
can you send your complete code
enhanced
!paste here
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.
totally not pycord in disguise
