#discord-bots
1 messages Β· Page 1127 of 1
π
u didnt do shit
im gonna go and let u 2 handle this
If you could use Google and Search for *GitHub discord.py" it might've helped you
Inb4 pr is doc change
@slate swan dont call other people do shit
So instead of saying that I did nothing, read and use your capabilities sometimes
Coding is not just about asking and getting everything the way you need it. It's about your own research and how to find things
read me*
arent we here for spoonfeeding, Krypton
Anyone could find within seconds how to install 2.0 if they would at least try it.
<@&831776746206265384>
this chat.
A mindset of a 12 yr old? See how you behave?
I'm giving advices on how to search things on your own
*!shh
silence iirc
!silence
β silenced current channel for 10 minute(s).
guys, stay on topic, no need to argue about frameworks
!warn 949145395274088489 you can't call out people names, just a warning this time for your language
:incoming_envelope: :ok_hand: applied warning to @slate swan.
!unhush
β unsilenced current channel.
@nocturne root same goes to you
.topic
Suggest more topics here!
Do bots even contain unique features nowadays
I had a bot to detect foul language using NLP and delete them
Iβve seen this same exact topic 3 or so times in a row now from .topic
Feels like every bot is a fork of another one
hikari cult you've done it once again
do what?
it only has like 6 topics, why dont you go and submit some
make dpy more native
to detect offensive speech
not really
sentences without foul words can also be offensive
a list with thousands of words? interesting.
totally not, people can use other variants and misspelt versions of the word
A word list isnβt sufficient enough imo, the English language is totally dependent on context so itβs kind of hard to tell without NLP
still better than a static list.
i find sarth is ||not|| ~~ cute~~ very offensive and a statement that isnt correct
π‘
Mine has AI based antispam idk if that's unique but I haven't seen any bots having better antispam yet
Well that's a fork
@torn sail it raises no errors
Of what
Antispam, just add some AI and your fork is done
exenifix is actually working on susventures V2
You can look at its source https://github.com/Exenifix/AIAS
open source 
V1 is not even out lmao
bro
ctrl + cπ
True, AI is not really a big part of it
"Download" is faster
git clone wtf yall talking about
just clone the repo and smack your token in it
git clone
this is*
Because itβs easy
i dont see okimii as the description or name of the channelπΏ
Get rid of the βdiscord-β in the name of the channel, itβll be a channel depicting you then
Ok.
Good one
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Go ahead there
Cool
Ye I released it today
12k samples of type text - is_spam preanalyzed
Analyzing is like finding amount of unique symbols, total symbols, unique words and total words. Pretty basic approach but works fine still
Depends on what you consider spam
Meaningless messages are undetectable by my system for example because it uses non verbal algorithm, repetitive words and symbols are tho, and that kind of spam happens more often
So lots people having a conversation would trigger that, it's the same case just not a bible.
i was wondering if i could 1 line add slash commands to my existing bot
With disnake or nextcord it's easy, just add different decorator and change your ctx to inter
i am using dpy
Dpy has a bit more difficult slash commands implementation and I can't help with it unfortunately cause I never used it
ah its okay
Trigger the anti spam, if it would have a trigger implemented the way you've described a potential "bypass"
Like let's say some hypothetical spammer joins your server with 10 different accounts and spams random bible verses. I don't think your bot would be able to detect it as spam unless you have heuristic checks in place as well.
Sounds like an alternative/change proposal to me
Discordians 4:3-2 - "get nuked haha"
import discord; client = discord.Client(intents=discord.Intents.default()); tree = discord.app_commands.CommandTree(client); @tree.command(name="command"); async def uwu(interaction: discord.Interaction): await interaction.response.send_message("you're uwu"); client.run("token")
what can I say except you're welcome
there's still more ways to do the same thing
yeah saw your gist ty
yeah I know you saw, welcome
wow i can see everything
why
ctrl +
is this good?
π
esoteric
esowtewic
uwu
π₯Ί
U sure?
What
uh-huh... a music bot
how I see it
and a fcuikging database
no build overwrite π
...?
you have no build overwrite to change your clients theme
you will get over the annie/dark phase
ew
bro
And this is OT talk
hunter mad build overwrites dont work on mobile
fun at parties are you
I already have enabled the Darker thing on Mobile
I don't remember the last time i went to one...
the darker thing
aka youve never been invited to one
Theme*
Typo
ok
Same thing
ok
My Bot Is Not Working ?? Can Anyone Please Help Me Solve This ?
import discord
discord.make_bot(moderation=True, music=True)
bot run
π π π
hard problem
ikr
man of culture
wtf did this do
everything is black now!!!!
how do i go back to light mode
click it again
now im curious, can you make your own build overrides
i clicked it and it scrolled down so i didnt see it
not right now
only discord devs can
if discord gave this feature to everyone to play with, discord would be a mess
that would be so funny
ASHLEY
web
π
hello I would need help for my bot that I spent on Linux and therefore I have an error that I cannot resolve ```py
Traceback (most recent call last):
File "/home/container/loadsub.py", line 14, in <module>
configs = json.load(config)
File "/usr/local/lib/python3.10/json/init.py", line 293, in load
return loads(fp.read(),
File "/usr/local/lib/python3.10/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.10/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 7 column 6 (char 173)```
can u show ur json?
{
"token": "",
"prefix": "An",
"status": "nice bot",
"suburl": {
},
"embed-color-text": "YAML",
"embed-color": 16777215,
"embed-config": {
"prix": "oui",
"vendeur": "oui",
"avis": "oui",
"localisation": "oui",
"marque": "oui",
"taille": "oui",
"couleur": "oui",
"etat": "oui"
}
}```
i delete my token
the error suggests that you have extra data in your json file
do you have something like this by any chance?
{
"token": "",
"prefix": "An",
"status": "nice bot",
"suburl": {
},
"embed-color-text": "YAML",
"embed-color": 16777215,
"embed-config": {
"prix": "oui",
"vendeur": "oui",
"avis": "oui",
"localisation": "oui",
"marque": "oui",
"taille": "oui",
"couleur": "oui",
"etat": "oui"
}
},
{...}
π bro just make a class for all these stuff
class BotConfigs:
token = ""
prefix = ""
``` and so on
dataclassesπ
metaclasses
π
class YamlToClassAttr(type):
"""
Tries to fetch data from config.yaml and making it class attr
Defaults to `Undefined` if the attr name is not found.
"""
def __getattr__(cls, attr: str) -> Any:
class_name = cls.__name__
try:
cls_data = DATA[class_name]
except KeyError:
print(f'{class_name} not found in `config.yaml`')
return
if attr not in cls.__dict__:
value = cls_data.get(attr, Undefined())
obj_type = cls.__annotations__[attr]
value_type = type(value)
# trying to convert the object to the type-hint
if value_type != obj_type:
try:
value = obj_type(value)
except (TypeError, ValueError):
raise NonConvertableType(
f'cannot convert {value_type.__name__!r} '
f"to '{obj_type.__module__}.{obj_type.__name__}'"
) from None
setattr(cls, attr, value)
return cls.__dict__[attr]
i love metaclasses but i never use themπΏ
YamlToClassAttr(type)
this kinda sounds cursed
idk what happens if you inherit from type
its makes a metaclass, its cursed stuff
cursed, yet awesome.
i love cursed stuff
go get a ouija board
π
there is already a ghost under my bed π³
exactly.
im not a ghost
you are, if you are not, why are you under my bed 
no.
why not
so we're all living in Ryu's house
yeah im under his bed, you?
in his walls
good spot
under his bed sheetsπ
AYO
asher freakyπ΅βπ«
thats it, im pulling out the ak
rip
get ready
AYO CHILL
idm as long as i don't creep the other guy out
i told, oki is ghost
no im a kawaii anime girl
you aren't a boy? π³
>>> oki is ghost
True
python doesn't lie
im a python interpreter
dynamic 
i understand youπ
>>> print(is_cute("ryuga"))
True
this channel has, once again, turned into oki's playground
it always was
!e print(0.2+0.7) # exceptions exist
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0.8999999999999999
i would catch you if you were a subclass of Exception
thats computers being bad

someone should !otn a okimii's playground
^
im going to sleep
!ot π
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
gn
imma BaseException
smooth
im SyntaxError
i can make you as red as the red tag of a syntax errorπ³
!pip pythonji wanna use this

π
ayo this is sick
the extension is .π
i wonder what would GitHub flag it as
import qt as Sarth
guys what are the methods of the sarth obj?
lmao
see the pandas import
wouldnt it be πji file.π
ya thats nice too
all I have is a exit_chat() method, and yes im a slotted class
import pandas as πΌ
guess what I can fit in your slots
BRO
interpreter knows best
hear me out
AYOooooooooooooooooooooooo
im going to get banned so im going to stop
yeah good
π
it's gonna be a mass ban
Suggest more topics here!
i wont stop in dmsπ
!ot before there is a blood bath here
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
carpet bombing
Put a server in the pipe bombs
im the smoothest person in the world when it comes to flirting so dont test me
not really
ok
this sounds like a lua user explaining which is lua better than python
:kek:
!ot always links to ot2, i thought it was random, life lie 
!source ot2
Unable to convert 'ot2' to valid command, tag, or Cog.
!source [source_item=None]
Can also use: src
Display information and a GitHub link to the source code of a command, tag, or cog.
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
!source ot
Sorry, an unexpected error occurred. Please let us know!
AttributeError: 'TagIdentifier' object has no attribute 'qualified_name'
Uh-huh
Sorry, an unexpected error occurred. Please let us know!
AttributeError: 'TagIdentifier' object has no attribute 'qualified_name'
bro
indeed
sarth ur turn
sarth are you worthy?
definately not
you probably are since youre a god
!src off-topic
Unable to convert 'off-topic' to valid command, tag, or Cog.
!source offtopic
Unable to convert 'offtopic' to valid command, tag, or Cog.
rip
π
!src src
Display information and a GitHub link to the source code of a command, tag, or cog.
!src
bro
wroooooooooooooooooooooooooong
im going to sleepπ‘
Sorry, an unexpected error occurred. Please let us know!
AttributeError: 'TagIdentifier' object has no attribute 'qualified_name'
!src otn
Add or list items from the off-topic channel name rotation.
!src abogus
Unable to convert 'abogus' to valid command, tag, or Cog.
π
i love you more, gnβ€οΈ
sweet dreams
gn
proceeds to talk in another channel
gn
actually sleeps
could anyone point me in the direction of a speech to text from discord call, in python? there is one, but its JS.
Hi
Bedause
How can we make our bot reply to the message?
Like this
ctx.reply()
ctx.reply()
π‘
!pypi SpeechRecognition
Duh
Oh, u already shared it
yes but in discord bot.
Sorry, my discord was lagging
Ok
anyone know how to extract image from assetbundles?
how could you make this work with discord my friend?
Well bro the only thing that you need from your bot is to get the file of the voice message
thats easier said then done, for example, where do you start and end a recording to not cut people off
wait you want to record a speech from a voice channel?
I got this error
Code
@commands.command()
async def translatereply(self, ctx,lang:str):
reply = ctx.message.reference
conten = reply.cached_message.content
translated = GoogleTranslator(source='auto', target=lang).translate(conten)
trans = discord.Embed(title=f"Tranlated to {lang}", description=translated,color=discord.Color.green())
await ctx.reply(embed=trans)
ctx.message.content ?
Oof
Oh then @paper sluice
Reply one is fine
?
Irdk I never used reference attribute
Help navi
the message is not in the cache
conten = (reply.cached_message or await self.bot.fetch_message(reply.message_id)).content
Ok will you Google it?
im in game, hold on
fetch message does not exist
conten = (reply.cached_message or await ctx.fetch_message(reply.message_id)).content
could someone give me a tiny example of this, it isnt working
its only gonna work in an embed description or a field value
yea thats what i have
like
Embed( title='python discord', description='foo, [hello](https://...)')
show code
lol it's markdown formatting
huh
Want to inject some flavor into your everyday text chat? You're in luck! Discord uses Markdown, a simpleΒ plain text formatting system that'll help youΒ make your sentences stand out. Here's how to d...
anything you type in discord, like code blocks, bold, italics its done over markdown, discord then converts that markdown into html and displays it
wait so can i embed links here
π
discord disables that for users
discord doesn't allow that
heyy
hey u free rn? i needed a lil help with my bot
ryuga is famous
@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"{message.author.name} deleted a message",
description="", color=0xFF0000)
embed.add_field(name=message.content, value="This is the message that they deleted",
inline=True)
embed.set_footer(text=message.author.id)
channel = bot.get_channel(channelid)
await channel.send(channel, embed=embed)```
i was trying to get my bot send time of message deleted in footer along with the id of the user but idk how to do
pride heart π
there's just three possibilities here
- either the message isn't in the cache
descriptioncan't be empty (just dont define description, simply remove the kwarg)get_channelis returning None (make a getch,bot.get_channel(id) or await bot.fetch_channel(id))
ps when you are using channel.send you dont need to specify the channel again
u can use datetime.datetme.now() to get the current time and send it in the footer
i wanted it to be bit like this one
I think I will just go away from here getting ignored every single time
no no no sorry
i just didnt get what u said
im like not that good at coding
im only ok ok
and that u said there i found it a bit confusing tbh π₯΄
this is the time at which the message was deleted?
yep
lol
lol
being ignored is part and parcel of being in support channels
do you know what can be done there
I'm just in depression
if u mean the date, its a "Unix Timestamp". <t:1656495247:d>
it not issue i just want it to send the id of the user and the time of message deleted in the footer
I have
@commands.command(short_doc='Short description', description='Long description')
but in the help command embed (I'm making a custom one) even tho I use
value=command.short_doc or "No short description"
it doesn't display the short_doc and it always uses "No short description"
the current code i made can only send the id of user idk how to make it send time with it too
like this carlbot
short doc is the docstring of the command's callback
!d discord.ext.commands.Command.short_doc see
property short_doc```
Gets the βshortβ documentation of a command.
By default, this is the [`brief`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.brief "discord.ext.commands.Command.brief") attribute. If that lookup leads to an empty string then the first line of the [`help`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.help "discord.ext.commands.Command.help") attribute is used instead.
just add it to the footer
embed.set_footer(text=f"{message.author.id} | {datetime.datetime.timestamp()}")
ok leme try that
!d datetime.datetime.timestamp
datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").
Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.
For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:
```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
``` New in version 3.3.
Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
π’ bro embed has a timestamp kwarg already
π
am high, but okay
which works like a relative timestamp
Ye
didnt do anythinh but break everything lol
@west veldt discord.Embed(timestamp= datetime.datetime.now()) do this
along with other arguments if you had any
when did that become a thing sarthak
bro i want it to send id of the user too
"along with other arguments"
read the next message
poor sarthak π
uh how to write both together
the footer and timestamp are divided using | or β’ depending on your device
oh ok
why together? its a timestamp and the Id would be a footer...
π it Always happens to me
π« I can relate
embed = Embed()
embed.set_footer(f"ID: {message.author.id}")
embed.timestamp = datetime.datetime.now()
why accessing the property afterwards instead of setting it directly while initialising
Β―_(γ)_/Β―
-impact of bad tutorials
@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"{message.author.name} deleted a message",
description="", color=0xFF0000)
embed.add_field(name=message.content, value="This is the message that they deleted",
inline=True)
embed.set_footer(f"ID: {message.author.id}")
embed.timestamp = datetime.datetime.now()
channel = bot.get_channel(channelid)
await channel.send(channel, embed=embed)```
like this?
that happens a lot here
!ot better place
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
what
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
o-
the event wont be called if the message is not in the cache, so I don't think that should be a problem
should this work?
hmm
import datetime
hi, what event would be appropriate for updating presence (hikari-lightbulb here)
nah it doesnt work should i send the whole code here?
define doesn't work first.
# Dont Forget:
from datetime import datetime
@bot.event
async def on_message_delete(message):
embed = discord.Embed(title=f"{message.author.name} deleted a message",
description="", color=0xFF0000)
embed.add_field(name=message.content, value="This is the message that they deleted",
inline=True)
embed.timestamp = datetime.utcnow()
embed.set_footer(text=str(message.author.id))
channel = bot.get_channel(channelid)
await channel.send(channel, embed=embed)
Worked by me
anyone, pls? π i don't want my code getting reviewed by an experienced person and seeing that i put presence in ready event
Depends on when you want to change it. If you want to change it time controlled you could use for example on_ready
if you want to set it once and not change it, i would just do it in StartingEvent
embed.timestamp = datetime.utcnow()
AttributeError: module 'datetime' has no attribute 'utcnow'
try datetime.datetime.utcnow()
not if u import it with from datetime import datetime
i would try:
embed.timestamp = datetime.now()
embed.timestamp = datetime.datetime.utcnow()
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
wew wew wew
^
it worked
I had to do StartedEvent since it wouldn't update, but thank you so much sir Ryuga
i thought i could ask here cuz this is #discord-bots π
Well when do you want to?
preferably at startup
I only know that in dpy the bot constructor takes an activity Arg for startup activity
ah ic
You can check if hikari has this
ya already solved, StartedEvent
but thanks
Hi
Hi
π
Hello π
Hello
how to make tracking services (online website, bot, api)
an example is in the photo
tasks? or the startup event
oh nvm you were already answered
we have sarthak uwu
Guys how can I make a pypi search command such that if it not found package on pypi so it return package not found.
either scrape the site, or use their (hidden?) API
Pypi api
Ik i can use json to load data but i want if it not found package it send package not found
!src pypi
Provide information about a specific package from PyPI.
then check for 404 status code
How to check?
if resp.status_code == 404
aiohttp
Ok
httpx πΆ
don't use that, bot.run/start takes activity and status kwargs. @paper sluice ^
you can use that
Aiohttp better ig?
ah its in run, i was tryna kind it in the constructor
find*
the view gets deleted with the message
but the instance is stored in code
ya but u can't really do anything with it because the message is gone
hmm, u can test it, delete the message then do view.is_finished() to check
when i write ''quoi'' , my bot say "FEUR", but when "quoi" is written in a sentence like ''de quoi ?'' my bot doesn't react . somebody have idea ? currently i use ''if message.content.lower() == "quoi":
await message.channel.send("FEUR")''
try if "quoi" in message.content.lower():
!d in
6.10.2. Membership test operations
The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).
For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
it work !!
@commands.command()
@commands.is_owner()
async def clone(self, ctx, channel_name):
existing_channel = discord.utils.get(ctx.guild.channels, name=channel_name)
if existing_channel is not None:
await existing_channel.clone()
await existing_channel.delete()
else:
await ctx.send(f'No channel named **{channel_name}** was found')``` instead of running !clone general I want to instead ping the channel name like !clone #general , how would I do this?
Typehint the arg
typehint it to what?
do channel_name: discord.TextChannel
thanks
doesn't work
show code
@commands.command()
@commands.is_owner()
async def clone(self, ctx, channel_name: discord.TextChannel):
existing_channel = discord.utils.get(ctx.guild.channels, name=channel_name)
if existing_channel is not None:
await existing_channel.clone()
await existing_channel.delete()
else:
await ctx.send(f'No channel named **{channel_name}** was found')```
remove the existing_channel thing, just use channel_name
its already a channel object
alr
u can change the name of channel_name to channel cuz that would be more appropriate
@commands.command()
@commands.is_owner()
async def clone(self, ctx, channel: discord.TextChannel):
channel = discord.utils.get(ctx.guild.channels, name=channel)
if channel is not None:
await channel.clone()
await channel.delete()
else:
await ctx.send(f'No channel named **{channel}** was found')``` like this @paper sluice ?
no, remove channel = discord.utils.get(ctx.guild.channels, name=channel), you dont need it
and then that's it?
ya
no
i justed tested it
ah well
so what is that happening
its basically doing discord.TextChannel('<channel_name>') internally
so it will do either #general or general
is there a way to only make it use #general
@paper sluice
I don't want any slash commands though
so you dk?
it's better to just make it input a channel while mentioning them
wdym
It does since it looks for the object and name.
You could also pass the id.
Then you'd need to make your own custom converter. Although I don't see what's wrong with allowing multiple ways to point out a channel.
^
alr sure I'll leave it as general and #general
it works
what happens if there are multiple channels with the same name
It will most likely pick the highest one in the hierarchy.
alright
As for the #... it passes the id so it will always be the selected one.
it clones all if general is passed, unless it's #general
thanks for the help anyways
How do I trigger a rule? Say rule #7?
!rule 7 this?
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
or do u want it for your bot?
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Thanks
π Bruh
Bro you pinged my '3 months ago' msg
Hats off
Can anyone look into #help-corn
Be patient, they are the most active channels and if someone can help they will
what is the most updated fork atm
spoon
fork, a classic from the early humans
has not received an update in thousands of years
it has i think in terms of materials
to make it :kek:
this is a spork
thats why its trash
spork is trying to be c and python at the same time
the analogyπ
rust
π you just proved its trash
Hello
Can anyone suggest a VPS for free which has nice uptime and all ?
Cause im thinking about shifting from replit to a VPs...
Give me slash commands for discord.py (PLEASE)
eh ?
Hey, I need help for Slash Commands with discord.py
can u gemme um... the github for it
You need d.py 2.0
^^
Cloud service providers like AWS and GCP have free tiers, but require a credit card to sign up
Yo. I am trying to make serverstatus, but when I am trying to get the file to check players this happens:
rip even heroku needs that otherwise only 550 hrs
all videos and articles regarding hosting on them are for node...
btw if I make a verified discord bot, will I get verified bot developer badge?
yeah
is this free hosting?
yes
how it works
it technically isnt
it's free upto $5
as long as u don't cross
I just need to host my bot
yeah
rude
ok but how
sorry my bad π
it shows paid..
what to do here
What kind of app
railway app
it's free till $5
Do they grant a whole server or just computing powers with no server
as long as u don't cross that limit it's free
and will my bot be hosted 24/7 inside 5$ ??
Guys how to fix this error?
Here is code
@commands.command()
async def pypi(self,ctx,package):
url = f"https://pypi.org/pypi/{package}/json"
async with aiohttp.ClientSession.get(url) as response:
if response.status == 404:
embesd = discord.Embed(title="404", description="package not found",color=discord.Color.red())
await ctx.send(embed=embesd)
else:
resp = json.loads(response.text)
verison = resp['info']['version']
summary = resp['info']['summary']
embesd = discord.Embed(title=f"{package} v{verison}",description=summary,color=discord.Color.green())
embesd.url = resp['info']['package_url']
await ctx.send(embed=embesd)
server i think
yes
Get is not a static method
it prolly won't even cross 1-2$
So?
unless u have heavy ram usage
cool and i can host 3-4 bots too ?
What can I do it make it work?
and how much database can it store under 5$ ?
You need an instance of ClientSession
but don't need to worry railway will kill the process if u cross $5
that means that it has something to do with the ClientSession object and has to be instantiated in order to work
π€
i never hosted more than one at a time so not too sure ask ashley
@slate swan ?
@robust fulcrum simply just add brackets after ClientSession lol
Oh cool and im stupid sryy....how many users data can i store ? π
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
message_id = payload.message_id
if message_id == 991482553959731352:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g: g.id == guild_id, self.bot.guilds)
if payload.emoji.name == 'roblox':
role = discord.utils.get(guild.roles, name="Roblox")
elif payload.emoji.name == 'minecraft':
role = discord.utils.get(guild.roles, name="Minecraft")
elif payload.emoji.name == 'brawlhalla':
role = discord.utils.get(guild.roles, name="Brawlhalla")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
message_id = payload.message_id
if message_id == 991482553959731352:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, self.bot.guilds)
if payload.emoji.name == 'roblox':
role = discord.utils.get(guild.roles, name="Roblox")
elif payload.emoji.name == 'minecraft':
role = discord.utils.get(guild.roles, name="Minecraft")
elif payload.emoji.name == 'brawlhalla':
role = discord.utils.get(guild.roles, name="Brawlhalla")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.remove_roles(role)``` Why doesn't this work?
idk read their docs
(aiohttp.ClientSession.get(url))
Like this?
Then sudo rm -r /their/app and shutdown their processes π
ClientSession()
Where would I get url then?
They can protect from that only if they don't grant user sudo access
ClientSession()
oh i was scrolled up
No i mean where would I get url stuff
As usual in your get method, that's OOP
Oof i forgot me in cog lmao
wdym by url stuff?
spork feed him
Does anyone know why this wont give me the reaction role?
π³
Not really related to what I said but ok
β
Yes the most correct one
async with ClientSession() as session:
async with session.get(url) as response:
...
await session.get() as resp:
I uhh think I will just go away from here
async with ClientSession() as ses:
resp = await session.get(url)
to_json = await resp.json()
^
Aiohttp code samples started raining down in the channel for a bit
lmao
i am on phone otherwise I would have typed to :kek:
@commands.command()
async def pypi(self,ctx,package):
url = f"https://pypi.org/pypi/{package}/json"
async with aiohttp.ClientSession() as session:
response = await session.get(url)
if response.status == 404:
embesd = discord.Embed(title="404", description="package not found",color=discord.Color.red())
await ctx.send(embed=embesd)
else:
resp = json.loads(response.text)
verison = resp['info']['version']
summary = resp['info']['summary']
embesd = discord.Embed(title=f"{package} v{verison}",description=summary,color=discord.Color.green())
embesd.url = resp['info']['package_url']
await ctx.send(embed=embesd)
Now?
That dude kinda thought that get was a staticmethod of ClientSession
I install "fivem" but when I write "import fivem" vscode doesn't recognize it
json.loads π
Yes seems correct but you can convert to json with await response.json()
why using json.loads? you can simply do resp = await response.json()
yes pretty much
nvm im slow
Anyway my brain slow today cause of a thing
ayp help me please
nice
π me using asyncio and aiohttp but i still don't know what's asynchronous
My brain was very slow when I was writing state machine behaviours and they were smoking grass
best make a connection object with the bot then use that throughout
There are some examples about good practices in their docs iirc
import aiosqlite
#async function uwu
conn = await aiosqlite.connect("uwu.db")
I got this error now
How to fix this ? π΅
I forgor does aiosqlite support pools
async def main():
async with aiohttp.ClientSession() as session:
async with bot:
bot.con = session
await bot.start(token)
asyncio.run(main())
rip indents
I wanted to use a rust function inside a python program in replit.
I understand that I need to create a library first to use it
what should be name extension and content inside files
to do it?
thats why i don't type in phone
How did you convert to json
I just used loads
u can do it in a setup hook to but that's longer to type
Use await response.json()
so it's tough in phone
I have read documentation on Google still kinda confused
Can any1 help me???? I did "pip install fivem" but my vscode thinks there is no module named fivem. I have already restarted vscode.
How can we close connection in aiohttp?
dunno
Too bad
bot is just a class u are only assigning a connection object as class variable
bot.conn.close()
It is closed automatically if you use async with construction
how can I store a variable whose value don't change even after bot went offline?
I got this error now
(A lot of errors) :X
pool is used for threading
hence completing the action of multiple tasks at one time
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
message_id = payload.message_id
if message_id == 991482553959731352:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g: g.id == guild_id, self.bot.guilds)
if payload.emoji.name == 'roblox':
role = discord.utils.get(guild.roles, name="Roblox")
elif payload.emoji.name == 'minecraft':
role = discord.utils.get(guild.roles, name="Minecraft")
elif payload.emoji.name == 'brawlhalla':
role = discord.utils.get(guild.roles, name="Brawlhalla")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
message_id = payload.message_id
if message_id == 991482553959731352:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, self.bot.guilds)
if payload.emoji.name == 'roblox':
role = discord.utils.get(guild.roles, name="Roblox")
elif payload.emoji.name == 'minecraft':
role = discord.utils.get(guild.roles, name="Minecraft")
elif payload.emoji.name == 'brawlhalla':
role = discord.utils.get(guild.roles, name="Brawlhalla")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.remove_roles(role)```Does anyone know why it's not giving me the reaction role?
async with bot:
async with ClientSession() as session:
bot.session = session
await bot.start()
i use this
There are plenty of ways, depending on your case. Usually the database is used for users/guilds data but for some config data you can use json
Show the error i guess?
Using Pool. The Pool class in multiprocessing can handle an enormous number of processes. It allows you to run multiple jobs per process (due to its ability to queue the jobs). The memory is allocated only to the executing processes, unlike the Process class, which allocates memory to all the processes.
Pls help how to fix it
No errors, just doesn't work
Database connection pool? So basically one connection can't execute multiple queries at the same time even if it's async (at least this is for postres) and creating connection every time you execute a query is expensive operation, pools just create connections faster
ya it is π
async code imo is disgusting
await
@robust fulcrum there is no errors
then subscript
Do we need to await response.json()?
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
message_id = payload.message_id
if message_id == 991482553959731352:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g: g.id == guild_id, self.bot.guilds)
if payload.emoji.name == 'roblox':
role = discord.utils.get(guild.roles, name="Roblox")
elif payload.emoji.name == 'minecraft':
role = discord.utils.get(guild.roles, name="Minecraft")
elif payload.emoji.name == 'brawlhalla':
role = discord.utils.get(guild.roles, name="Brawlhalla")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload):
message_id = payload.message_id
if message_id == 991482553959731352:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, self.bot.guilds)
if payload.emoji.name == 'roblox':
role = discord.utils.get(guild.roles, name="Roblox")
elif payload.emoji.name == 'minecraft':
role = discord.utils.get(guild.roles, name="Minecraft")
elif payload.emoji.name == 'brawlhalla':
role = discord.utils.get(guild.roles, name="Brawlhalla")
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
if member is not None:
await member.remove_roles(role)```Why wont I get the role from the reaction, is there something I'm doing wrong, there are no errors?
2.0 is max level async compared to previous ones idk they made async everything possible
My comamnd working now!
Any1 has any idea why my vscode isn't recognizing "fivem" as an import? I did "pip install fivem"
because its vscode
that isn't really related to #discord-bots , ask in #editors-ides
lmao
it is needed for my discord bot
no help?? D:
Like I said yesterday, it probably has to do with how you're comparing the emoji names. Try comparing IDs instead
alright but do u see any other errors that could possibly in the code?
Use bot.get_guild(id) instead of guild = discord.utils.find(lambda g : g.id == guild_id, self.bot.guilds)
and also use guild.get_member(id) instead of member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
async def main():
async with discord.Client() as client:
async with aiohttp.ClientSession() as session:
client.session = session
async with aiosqlite.connect("file.db") as connection:
client.connection = connection
await client.start("token")
try this
Guys give me a challenge for a command in my discord bot (I'll make the comamnd which you give me for challenge)
Make a good bot core/bot base infrastructure so that it's easily expandable π
Probably a better way than nesting 3 context managers would just be to call them individually, and use .close() on each of them afterward
@sick birch
I asked for command challenge not for bot
i do like this in hikari
async def set_http_connection(self, event: StartingEvent) -> None:
""" Setting up the ClientSession just before the bot connects to discord """
self.session = ClientSession()
def close(self):
""" Closes the ClientSession before closing """
self.session.close()
super().close()
u can setup multiple in the setup_hook then close it with the bot
^
make a interactive poll command woth graphs
Yes.. but what I mentioned I don't see people focusing on a lot. Would be nice to actually have it though
Same as now, bind it to your client instance
PoV: They use 3.9
Easy with pyplot
I'll do it
not pyplot use reactions
Till tommorow
Ik but result using pyplot graphs
make a bar graph either horizontal or vertical
u can use the squares available in reactions
Will pie chart work or line chart?
i dont think u can make pie chart or line with reactions
Piechart would be more good
just make one with reactions as a progress bar
I'll use piechart after making command
alr
@shrewd apex how much should be max values ?
Like max number of options in a poll
10 ig?
10
sure
How can I make arguments optional?
Oh k
Like we do in other commands
For now i sleep I'll start making tommorow
https://c.tenor.com/5QJCAjuvpYEAAAAi/not-gonna-make-it-low-battery.gif
Good night sweet dreams
Ok
how can I include all text after getting the variables in the message one so i can use
$session saturday 2-7pm I SEE YOU
i need the i see you to be in the message var
@commands.command(name='session', description='Sends the session information for duengeons and dragons this week')
async def session(self, ctx, Day, time, message):
embed = disnake.Embed()
embed.title = f"**Session Information**"
embed.description = f"Dnd session information for this week.\n\n**Day:** {Day}\n**Time:** {time} \n**Message:** {message}"
embed.set_footer(text="Notification System")
embed.set_author(name=f'{ctx.author.name}', icon_url=f"{ctx.author.avatar}")
await ctx.send(embed=embed)```
async def session(self, ctx, Day, time, *, message):
this puts all the text after time inside message
ok thank yoiu
slash commands are better than normal ones, in every way. Change my mind
No custom converters
yeah one thing i like is u dont have to add checks for what the user is inputing
guys how to check if a user has any of these roles?
example please
I'm doing it like this, it seems like its not working:
@commands.has_role([1234567899,125125215,12509095,35215215])
For an example, having a time converter for mutes
Emoji converters, etc
Code block cleaner converters
i would just make a converter and type hint with that
Yes but with slash commands you cannot!
hey
i wasn't aware of that, wow ok ig it makes sense, discord doesn't allow you to enter the wrong type
are you trying to check if the user has any of those roles or all of those roles?
Any of them
ig u can accept it as a str ( or some other basic type ) and pass it in ur convertor, but yea they are extra lines
then you should use the other decorator @commands.has_any_role(1, 2, 3, ...)
note that you dont need to pass it as a list
in fact the has_role() check is only meant to take a single ID/name
alr thanks
d.py 2.0 does support transformers which let you start with one of the builtin types and let you transform it afterwards, so the syntax would end up similar to a custom converter, albeit without being able to instantiate the transformer
What are the possible reasons this can occur when setting a local file as the embed image? (stuck loading)
Did discord.py make them work in slash commands?
I mean, the normal converters would work. Iβm thinking about custom ones rn with no type affiliation to discord
broken image
corrupted most likely
well yeah 2.0's transformers are the slash equivalent to converters in text commands
Iβm asking if custom ones work
Cause discord requires a type enum to be passed to the API when registering
Of course, you could always just force all custom converters to be of STRING type
transformers are custom
you can specify what type you want it to be on discord, and the transform classmethod will receive the corresponding type
e.g. ```py
class EvenNumberTransformer(app_commands.Transformer):
@classmethod
def type(cls):
return discord.AppCommandOptionType.number
@classmethod
async def transform(cls, interaction, value: int):
# converter code here```
portal sprites are drawn, think they turned out nice 
ya they work in hikari as well, i was a little confused when u said that
there's an invite link generator in the OAuth2 -> URL Generator section in the discord developer page
go to there, select the "bot" scope (and applications.commands if you're using slash commands), pick your server permissions and the link will be on the bottom
Probably just my confusion, I did look at the internals of application commands until now
It asks for a custom uri and i have no clue how to use that.
the URI is only needed if you use scopes other than bot/applications.commands
at least afaik
all good π
U clicked on "URL Generator"?
Dear. I try to start the bot, it gives an error
need help to create a embed command.
my error: AttributeError: 'Client' object has no attribute 'command'
message_content was introduced to discord.py in v2.0, so i would guess you have dpy 1.7.3 installed
you have to make prefix commands with Bot not Client
update your discord lib
i use bot.command
....?
discord.Bot your bot is? is it not?
I found the error
oh. please tell me how to update
pip install -U discord.py?
not exactly
sorry
2.0 is in github and has not been released
i don't use dpy i use disnake, not sure
you would need to do pip install git+https://github.com/Rapptz/discord.py
and ofc you would need git
iirc ashleys tutorial shows how to upgrade to 2.0 @slate swan check pins!
Can I make a bot to check if a bot went offline or not ?
Bot1 - checks if bot2 is offline
If true : then bot1 sends alert
Else : well nothing
thats fine we all make mistakes!
Btw do u know it when it will be released?
well im not sure but my estimate would be later on to December or October, you can ask danny but he will probably say theirs no coordinated day
Damn, do you need to install git too?
Hm ic ty
^^^
yes if you're using git+link
that is so.
oh how
!d discord.Member.status
property status```
The memberβs overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
You want to use a task loop for that i guess
@slate swan https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#install-the-latest-version-for-discordpy
Can i fetch my own bot's status? cause it always returns None, i don't know if it's possible to get the bot own status
why you should want to get the status of your own Bot
In the proccess of building a bot what term would i use pull a username {user} or {player}
only real attribute you can use is Bot.status which thats the status uppon logging so you would need to use Member.status
Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.
it can return a member object of your bot so just check the status with Member.status
!d discord.Member.status
property status```
The memberβs overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
depends, user in discord is just a discord user, member is a user object but just in a guild and player is a participant of a game
@tasks.loop(seconds = 60) # repeat after every 60 secondss
async def myLoop():
await bot.wait_until_ready()
async with aiohttp.ClientSession() as session:
csakmegnezni = 0
async with session.get('http://87.237.52.47:30226/players.json') as response:
csakmegnezni = 1
if csakmegnezni == 0:
print("nem lepett bele a kodba")
else:
print("nincs remeny")
myLoop.start()```
Yo. This is just a test, and nothing is being printed, but "csakmegnezi" should be printed.
Should be == 1
Yea but if object = 1 print object or if object == 1 aka true print object
The terminal is still empty..
Find where its stopping and recorrect it there
Does discord.py have support for buttons in embeds?
yep
What i thought thx
wdym
I tried looking for it a while ago
couldnt find it in the documentation
I mustβve missed it
Code runs but no output prints it means it working but it doesnt send output because it stops somewhere add print to few lines and find out where stops and you can fix the err there
@slender cypress u mean like this?
the only thing that would print is the first if statement and it wont because, since youre doing starting a session with aiohttp and then making a request the context manager probably closes and ends execution
What i thought lol its like hey do this and has no other commands saying well running this do this to
Yep
yeah thats my only logical answer
also, how would I make a bot listen to all messages until a certain keyword is typed?
i tested it out and thats the only reason why it would behave like that, the parent context manager got closed after the first request lol
I added a bonus print (print ('asd2'). And it is get printed so we know where is the error
@tasks.loop(seconds = 60) # repeat after every 60 secondss
async def myLoop():
await bot.wait_until_ready()
async with aiohttp.ClientSession() as session:
print('asd2')
csakmegnezni = 0
async with session.get('http://87.237.52.47:30226/players.json') as response:
print('asd')
csakmegnezni == 1
if csakmegnezni == 0:
print("nem lepett bele a kodba")
else:
print("nincs remeny")```
^
oh
Add while true statement
no no
this was only a test
you can always open the session without context managers and close it yourself
Dear. installed git via installer restarted PUTTY and it still doesn't install
It would work but it would be a banded
well do you have git in your path?
So I wanted to know what it prints if the server is offline
it would be bad
add to the last line discord.py.git
anyways got to go, cheersβ€οΈ
bai
In theory yes
It?
I'm so confused... why am I getting this error in pycharm with the exact same scope and the exact same object as the method above already using sp?
hey guys
how i can make my bot that in a selected channel when someone say hello it says hi
?
i want to make a change presence command, if the status parameter is not filled, it'll use the current bot status
make a on_message listener and add a check if message.channel.id == ur channel I'd and message.content == "hello" then send message.reply("hi")
It didn't reply for some reason, @warm tulip
still out of town? π
one more week
lol
well it would be something like this if youre wondering
if ctx.me.status == new_status:
return await ctx.send(...)
return await bot.change_presence(...)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
okay ty
await ctx.send(...)
return
π
looks cool ill give it a try

It's mostly cool until you see the themes
the function is most probably type hinted with -> None so thats more appropriate
Simply read the error

