#discord-bots
1 messages Β· Page 1086 of 1
!e ```py
class A:
url = "cutegif.png"
list_ = [ A() ]
link = list_[0].url if list_ and list_[0].url.endswith("png") else "No"
print(link)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
cutegif.png
what do you mean
HTTPS is a protocol, itself being a set of procedures & rules for internet communication
python conditions have an and keyword
So, yes it is a protocol
That's what I meant π
yes, do you want me to do and attachment.endswith
yep!
can I do .endswith['.jpg', '.png', '.jpeg']
but okimmi's gonna flex his vocab
π³
im eating cereal
i realise that i have my CS exam in a week and i haven't started that chapter yet
best cereal is frosted flakes
wrong brackets
capppp
Too much to remember π«
is it the ()
you guys give exams? π
cinnamon toast crunch > any cereal
frosted flakes are literally the best things I've put in my mouth
π³

oh wait nvm, I have my CS exam tomorrow too 
Pause
π
.endswith(("string1", "string2"))
Ah ok
yeah, boards
Lol
.topic π
who dosent?
Anime images
@Ashley V ketchup
another global emoji?
I' d rather not answer before I start making dark jokes
its nitro this time
for attachment in message.attachments:
if (
attch.filename[-4:] in ['.jpg', '.png', '.jpeg']
and str(message.channel.id) == str(channel_id5) and attachment.endswith((".jpg", ".png", ".jpeg"))
):
does this look right
π₯Ά
oki
since when does a God read a book? no need when you know everything
π³
π
just to enroll into edens'
There is always something to learn, even for a master
fair enough
someone 
You in 12th grade right ?
why don't you run it and see y9su
mhm yeah
oh yeah it's almost like it's one button click π€£
rich peeps 
Cbse ?
same here i need to check the oil in my bots engine
i prefer using simple evals on discord for these purpose
no lmao
yep

what can I add for a finally? I don't really need anything to happen after
Try it
return statement is usually the "not anything to happen after"
Unfortunately not all of us can simulate code execution in our brains faster than a computer
hm it seems it didn't do anything after sending an image..
make dummy classes and run it on @unkempt canyon 's evals
or the value(s) to be sent back by a function
wait you guys dont have a python interpreter in your brain?
Whats attach
yeah
Do you mean attachment
yeah I changed it to attachment
Snoggy being the 3.10.4 interpreter
π
it would be good if i even had an calculus calculator let alone python interpreter
Lemme show my code I probably have something wrong
π
why would you check things again and again?
if attachment.filename[...] is the same as using .endswith, and why would you convert integer ids to strings and check those when you could simply compare integers
@client.event
async def on_message(message):
try:
if message.author.bot:
return
channel5 = discord.utils.get(ctx.guild.channels, name="testchannel")
channel_id5 = channel.id
for attachment in message.attachments:
if (
attachment.filename[-4:] in ['.jpg', '.png', '.jpeg']
and str(message.channel.id) == str(channel_id5) and attachment.endswith((".jpg", ".png", ".jpeg"))
):
with open("info.txt", "w+") as f:
f.write(attachment)
finally:
return
my brain just turned on
get(ctx.guild...)
nice
oh yes very nice..
should be message
why is there a try block?
you should simply handle the errors instead
well for now I just wanna get it to work
bad practice
I know I know
is it still impossible to attach files to a slash command
@slate swan just use this
that looks so complicated
if you guys find out whats wrong here ill send you a funny cat meme
def foo(bar: list["Any"] = []) -> list["Any"]:
return bar
```πΌ
Pretty good
could you just help to fix my code?
Stop π
nothing ig...
given that typing.Any is imported?
their is, its a tricky basic problem andy showed me
nope
come sarthak i know you want that funny cat memeπ΅βπ«
it's with the -> list ['Any'] ig not sure
help me π₯Ί
nope thats a return annotation!
!pep 484
no, you can
No clue
π
Does it relate to None?
ok ill say it so no funny cat meme for anyoneπΎ
nope
it should not be returning list[Any] ig
def foo(bar: list["Any"] = []) -> list["Any"]:
return bar
the bar argument is created on the function declaration and not when called so it shares states everytime you call itπ
πΏ
Oh that
and..
whats wrong with it?
nothing its just a tricky problem you can encounter π³
except for the bar variable acting like a.global
I don't think Attachment objects have a endswith method that's for str
Oh?
ποΈββοΈ
isnt that invalid syntax?
I think I needa start from the bases I confused myself
I think there is no dot before [0]
yea
oh hm
if message.attachments[0].url and message.attachments.endswith(("jpg", "png", "jpeg")) if message.attachments else "No image provided"
@slate swan ?
should work
thats just an condition check though, not a variable assignment
yeah how would I actually implement this?
the syntax is improper
variable = value1 if condition else value2
``` is the syntax
so I cant make it all into one variable?
i just sent it thrice, you find that complicated
Kinda
you find that complicated
i just sent it thrice, you find that complicated
π
what
i am sending a mention through a webhook, but the mention i'm sending will change so i can't copy the id manually
hm?
@slate swan Ok I just did something it might be completely wrong
i told you earlier its a word 
@client.event
async def on_message(message):
try:
if message.author.bot:
return
channel5 = discord.utils.get(message.guild.channels, name="testchannel")
channel_id5 = channel.id
if int(message.channel.id) == int(chanel_id5):
if message.attachments.endswith(("jpg", "png", "jpeg")):
attch = message.attachments[0].url
with open("info.txt", "w+") as f:
f.write(attch)
else:
attch = "Invalid image type"
else:
return
finally:
return
@slate swan
its old englishπ‘
old like youπ
message.attachments is a list you can't use endswith on it
im just 17 
old
what if I do message.attachments[0].endswith
will work, but if there's no attachments , be ready to get ur shell spammed
yo, the code for my music bot works on my pc but when i run it on AWS i get a huge error and
[https @ 0x622e400] HTTP error 403 Forbidden <huge link> 403 Forbidden (access denied)
so again, it works on my pc but on the instance it gives 403 Forbidden
Oh.. it wont literally break the bot though?
if <check if message has images> and <check first Attachment's url>:
``` is what id do
nope
ok
I tried it and it didn't error out but it didnt create a txt file
I forgot to add the .url π
nevermind it still doesn't work wtf
@client.event
async def on_message(message):
try:
if message.author.bot:
return
channel5 = discord.utils.get(message.guild.channels, name="testchannel")
channel_id5 = channel.id
if int(message.channel.id) == int(chanel_id5):
if message.attachments[0].url.endswith(("jpg", "png", "jpeg")):
attch = message.attachments[0].url
with open("info.txt", "w+") as f:
f.write(attch)
else:
attch = "Invalid image type"
else:
return
finally:
return
@slate swan didn't make the txt file or error out
you're not allowing it to raise errors why would it?
I misspeled channel
...
pretty sure such a huge check is unnecessary
still didn't work
let it give an error
Where π
cuh?
yes
you are 'cuh'
don't call me that cuh
(lambda:(["no"],attachments[0:1])[getattr((attachments[0:1]or"*")[0],"content_type",None)in{"image/png","image/jpeg"}])()[0]
```one-lined
does utils.get(message.guild.channels, name="channelname") get the channel id?
π₯
if not how do I actually get the id from a oneline like iths
its message.channel.id otherwise where you gonna get channel from
channel5 = discord.utils.get(message.guild.channels, name="test-channel")
I need to get the Id of this channel somehow though
just do message.channel my dude
for both?
I need to check which channel the image is being sent
so if it's sent in general I dont want the rest of stuff to happen yk
yea
so the message.channel.id == certainchannelid
then just do if message.channel.name == 'cuh':
!e ```py
print((lambda:(attachments:=[type("_",(),{"content_type":"image/png"})],["no"],attachments[0:1])[(getattr((attachments[0:1]or"*")[0],"content_type",None)in{"image/png","image/jpeg"})+1])()[0])
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
<class '__main__._'>
what the-
editing this aint gonna change the output bruh
@scarlet sorrel thanks cuh u genius fosho
np cuh
Editting within a time frame does re-run the REPL
I just didn't edit it fast enough
!e print("bar")
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
bar
so no one knows about this?
@commands.command()
async def botstatus(self, ctx, stat: typing.Literal['online', 'idle', 'dnd'] = 'online', *, activity='Working'):
mapping = {
"online": discord.Status.online,
"idle": discord.Status.idle,
"dnd": discord.Status.do_not_disturb
}
await self.client.change_presence(
status = mapping[stat],
activity = discord.Game(activity)
)β
boom :D
nice
Playing Working would be cursed though
_ some sort of
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='+', intents=intents)
@bot.event
async def on_ready():
print("Online!")
@bot.command(pass_context = True)
async def ping(ctx):
await ctx.send("Pong! Your ping is " + str(bot.latency) + ".")
token = '(token)'
bot.run(token)β
would add annotations to the other arguments and i would use wait_until_ready
mapping is constant, load it once
in the init or something
wdym
like make it a class variable instead of making that dict everytime the command is invoked
why is it not imported
U can also do discord.Status["online"] since it's an enum
Got it! Ty
anyone know about music bots? because im getting this error when i try and play a song
Server returned 403 Forbidden (access denied)
help me
Btw i 'm too facing the same issue
just stop making music bot, get urself spotify or something
Having problem in source codes of music ones
i dont really see why it would be a problem but its a good idea
u stoopid
it was a joke bro
you got no friends for sure
improvise adapt overcome
He's correct tho, music bots are against ToS @scarlet sorrel
not u as a friend
why do you guys get aggressive over a joke?
you do got a point
you cant listen with multiple people on spotify
premium
Nevertheless, music bots are still against ToS
The truth which everyone knows but showing off is another perspective for it
its only <rm10 with family package
yea and a bot is cheaper so...????
!e
def a():
print(b)
b = 1
a()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | File "<string>", line 2, in a
004 | UnboundLocalError: local variable 'b' referenced before assignment
and u get access denied
thats is your error no?
its a problem to be solved, not like you would know much about that considering you probably just fall down at the first hurdle with everything in your life
@scarlet sorrel calm down please
he started it
from progress import my_emote
from progress.my_emote import *
@bot.event
async def on_command_error(ctx, error):
e = my_emote(ctx)
if isinstance(error, commands.MissingRequiredArgument):
elif ctx.command.name == 'trade':
tradelist = f'''
**__Bob, the Builder__**
~~None~~
**__Wagner, the Blacksmith__**
{e.emerald}emerald -> R
**__Skev, the Lumberjack__**
{e.emerald}emerald -> {e.small_sapling}small_sapling
{e.emerald}emerald -> {e.apple}apple
**__Sarth, the Butcher__**
{e.emerald}emerald -> {e.cooked_pogchop}cooked_pogchop
{e.emerald}emerald -> {e.steak}steak
**__Ashley, the Cleric__**
{e.emerald}emerald -> {e.cleansed_dirt}cleansed_dirt
{e.emerald}emerald -> {e.cleansed_water_bucket}cleansed_water_bucket
**__Greg, the Farmer__**
{e.emerald}emerald -> {e.potato}potato
{e.emerald}emerald -> {e.wheat_seeds}wheat_seeds
{e.emerald}emerald -> {e.carrot}carrot
{e.emerald}emerald -> {e.beetroot_seeds}beetroot_seeds
**__Ryuga, the Shepherd__**
~~None~~
'''
embed = discord.Embed(
description = tradelist,
color = discord.Color.blue())
embed.set_author(name= f"{ctx.author.display_name}'s trade(Buy)",
icon_url = ctx.author.avatar.url)
await ctx.send(embed=embed)
but i didnt start to fight with u?
if u cant take jokes then dont talk with pepo out there
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
!rule 5 for your discord bot then (:
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
please calm down
btw @slate swan
What's the issue?
show my_emote
Why is my name there, I feel special now
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.
wtf
i wondered will u shout at me and tell me to remove ur name π€£
im confusion, what is my_emote?
Nice, sarthak and Ryuga also there
dog damn
u wanna join?
I'm fine
farmer builder or blacksmith
where?
π
nah, I'll be fine, there are a thousand people with the same name, might consider replacing mine with Hunter's
@paper sluice
π€£
i legit yeet all my custom emote here
**```py
Hey, Discord peeps!
What's this?
thats My_emote what is my_emote?
server monetization? or what
oops
That server monetization sucks!
It's now also a mysery to me
Nice
What to do with
its working now
thanks :D
you know that instead of doing all that in the init you could have used class variables right?
π
okimii's*
im just lazy
Lmao
same thing
its actually less work
No we ain't same
just take all of the school books to the school
instead of taking only the books that i need to use that day
Lazy to do less work
@maiden fable I actually made the MaybeAwait decorator working with instance methods
π
class MyEmotes:
emote1 = "ποΈββοΈ"
``` shorter work
Bill gates will be proud
Nice, now I would love to see how people start to criticize anyone who uses that in their lib
Especially people in the discord.py server's general chat
can we talk about some sane judgement server
me who doesnt even know what is that π
But its cool :c
guild_ids = [956462089935941652]
@bot.slash_command(guild_ids=guild_ids)
async def test(interaction : Interaction):
channel = 982876955554771014
await channel.send("Test")
If I have the channel.id stored in a database, how would I send a message to that channel?
I just made this command as an example of the issue, not sure how to fix it.
AttributeError: 'int' object has no attribute 'send'
hello Scofflaw π
:wave:
Those are the people who criticize others for useless reasons
!tempban 944202890015277106 1w This isn't an acceptable way to treat people. Please take our rules and code of conduct seriously if you decide to return.
:incoming_envelope: :ok_hand: applied ban to @scarlet sorrel until <t:1655012509:f> (6 days and 23 hours).
People in dpy server don't know the definition of "cool"
dont temp ban him
If I stored the channel name, would it work instead?
dpy server is the definition of "if you don't do it my way you're not cool"
It's so that u can do:
get_member -> Fetches from cache
await get_member -> Fetches from API
why cache???
So your bot isn't slow
Oh, my bad
π₯²
And by "my way", it's the traditional ways. No new ideas
:D
Wym?
u wanna join?
i tihnk they're asking why dpy has a cache feature
dynamic = slow
My code sucks
what if user is not in cache
i wonder why
Nonono that's now what I mean
same
remove it before pepo scolds at u
yeah
I'd much rather had used some other method than looking at the callstack though
Plus regex is slow
u want farmer?
Indeed
i am fine with anything
I think okimii would also love it if u add him to the list
or statement be like
I saw you used c api, I have 0 experience with that
It's just a better syntax sugar
Lmao my name don't tho
hunter the hunter....
Font*
sad bob noises
Hunter, the Huntering
LOL
lmao
Huntering the Hunter
Hunting the Hunter
hunter the setattr
# -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
from ctypes import POINTER, py_object, pythonapi
pythonapi._PyObject_GetDictPtr.restype = POINTER(py_object)
pythonapi._PyObject_GetDictPtr.argtypes = [py_object]
async def main() -> None:
async def _get_member(id: int) -> None:
print(id)
def __await__(self):
return _get_member(123).__await__()
def get_member(id: int) -> None:
print("sync")
mapping = pythonapi._PyObject_GetDictPtr(type(get_member)).contents.value
mapping["__await__"] = __await__
await get_member(123)
asyncio.run(main())
``` heres the code
Lmao Hunter, the Hunter
You should know that not everyone is as genius as u r, andy
Successfully overrides await but the await get_member doesn't call it!!
u want to become blacksmith or builder
So I could not get it to work
I also tried overriding call, same issue; get_member(...) wasn't calling it
Sad
We are tryna make it so that if u call get_member, then it will fetch from cache and if u await the function, it will fetch from api
oo ok
This is, in no way, related to dpy
I also disassembled it to see the bytecode so I for sure know it wasn't calling call or await
I don't know enough of how functions work in the backend so I'll just giveup
andy, is it just me or u r doing Python since u were born?
No
The amount and level of knowledge tho
There are a lot of people who know more than me
such as andy, andy, andy, andy, andy, andy and andy
And the PSF core devs
im pro at being noob
Maybe better than me 
U can ask here
nono u better
idk how to output hello world
code
Can u take the commands to #bot-commands please?
ok
I just needed to ask the Meaning of discord from him 
#bot-commands
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
asking u whether do u want to be a blacksmith or a builder
ur famous
choose one
π
Make him villager
:/
villager with nothing
nitwit?
You all are
this colour reminds me of something...
!ot last
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
F sry btw
villager
!ot :)
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
Like this?
go cry in corner old topics
Soon#3
>>> list(discord.Intents.default())
[('guilds', True), ('members', False), ('bans', True), ('emojis', True), ('integrations', True), ('webhooks', True), ('invites', True), ('voice_states', True), ('presences', False), ('guild_messages', True), ('dm_messages', True), ('guild_reactions', True), ('dm_reactions', True), ('guild_typing', True), ('dm_typing', True), ('message_content', False), ('guild_scheduled_events', True)]β
an eject button that makes my bot explode
disconnect from the gateway*
huh
@slate swan Can i use words such as ||Nukes|| here?
Yes π
why ping me
bot inside bot inside bot
Btw nuke & apocalypse sounds same
This mean u are a raider ?
If anyone can help me with Bot dashboard... Pls
apocalypse is greek for revelation
Yes?
Naah buddy not at all
I don't hve any extra tags or differently designed name
Should we rather create our own Web support of bot or depend on some other servers?
discord server better
||Regarding this just have a look at "about me"||
Yupp i have one added into 45 servers with 67k users overall!
But Have less staffs for the same, hence i'm some sort of confused right now
Well u need staff to help ppl online too
still discord server is my choice
*web based bot with most Faqs
Ye faq u can put it on a website
Will think of it too (||if recuitmore staffs in Future||)
Yupp that's what i was thinking of
@slate swan u still finding a hosting?
Ye ;-;
Sad
lmao
I'm thinking of trying termux
@slate swan which Bot
nuke bot
Termux is not a host
Ye
Good idea actually
please just buy a raspberry pi or host on AWS
Cant
Repleeeeet
Bro, RPIs are expensive asf
Linode/AWS is an option
Do one thing...
..
Ye that's what I'm talking about
I have downloaded it now and I have no idea what to do actually
download your code and install deps?
pkg install python
There are a few tuts on yt
Alr lemee check yt
install python, make venv install packages and run the bot
TIL @heavy shard's pfp is animated
don't use termux off google play, it's outdated, use termux from f-droid
it sticks tongue out π
Ummm, got it now after 15 mins. Of successful thinkingπ
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
Talking about bot hosting is related to discord bots tho
Wrong reply
My bad
Hahaha, I just saw the eyes
hunter
#965291480992321536 is a thing
where is that embed !
the in keyword is faster with sets correct right?
yes
Yes
cheers
Nvm, not wanna argue
Yea
isn't there a & to check for set intersection
iirc yes
MEE6 is using disabled buttons to decorate msg
Sparky: can i pm you?
pm?
Oh..
Private
I understand
can anyone send me the source code of dpys (2.0) async context manager? i see it no where.
which one
?
Need help with #965291480992321536
okay? just ask your question and wait for someone to answer
Did it
From a while
https://github.com/Rapptz/discord.py/blob/db5a22d7912557c55fc047f30f42ef10b6a63289/discord/context_managers.py#L52 @slate swan because you didn't specify which one, this is the .typing context manager
discord/context_managers.py line 52
class Typing:```
https://gist.github.com/Rapptz/6706e1c8f23ac27c98cee4dd985c8120
# After
bot = commands.Bot(...)
async def main():
async with bot:
bot.loop.create_task(background_task())
await bot.start('token')
asyncio.run(main())
this one
contextlib.asynccontextmanager
sorry i didnt specify it
https://github.com/Rapptz/discord.py/blob/db5a22d7912557c55fc047f30f42ef10b6a63289/discord/client.py#L249 the aenter and aexit are defined on Client
discord/client.py line 249
async def __aenter__(self) -> Self:```
which ext.commands.Bot inherits
Yes
weird i pressed ctrl+f and check that file and it never detected it, oh well, thanks!
github's jump to can be pretty useful for stuff like this π
ah never knew that, thank youπ
Currently I am doing a on_reaction_add to get the number of reactions on a poll message.
Would I be able to, instead of doing x for each reaction add, have it do it every y minutes?
const { joinVoiceChannel, createAudioPlayer, createAudioResource, NoSubscriberBehavior, AudioPlayerStatus } = require('@discordjs/voice');
const { MessageAttachment } = require('discord.js');
const googleTTS = require('google-tts-api');
module.exports = {
name: 'tts',
async execute (client, interaction) {
await interaction.deferReply({ ephemeral: true });
// get audio URL
const url = googleTTS.getAudioUrl(interaction.options._hoistedOptions[0].value, {
lang: 'en',
slow: false,
host: 'https://translate.google.com',
});
const tts_message = new MessageAttachment(url, "tts.mp3");
if(!interaction.member.voice) return interaction.followUp({content: "Please join a voice channel.", files: [tts_message]});
if(!client.isReadyForTextToSpeech) return interaction.followUp({content:"Please wait until the last message is complete.", files: [tts_message]});
interaction.followUp({files: [tts_message]});
you can probably just wait for the poll to end and check the reaction objects and just check the amount of members that have reacted with that emoji
this is a python server...
it's not a timed poll
I used ```py XD
but how would I get the message object? I know about that, but there are multiple polls
so message object of each poll
im thinking about something but its probably hardcoded so nvm
is it not possible?
no it is
can you give a rough example of the hardcoded one mentioned above?
async def pollchecker(message: discord.Message, checktime: int) -> None
poll_message = await message.channel.fetch_message(message.id)
while True:
if len(poll_message.reactions[0].members) > len(poll_message.reactions[1].members)
print("first reaction is winning!")
else:
print("second reaction is winning!")
asyncio.sleep(30)
@bot.command()
async def makepoll(ctx: commands.Context, *, topic: str) -> None:
msg = await giveawaychannel.send(topic)
...
bot.loop.create_task(pollchecker(msg, 30))
bad pseudo code imoπΏ
Hi how can i add like has_permissions(ban_members = True or kick_members = True)
the pollchecker here would be called every 30s right?
depends on the time yes it would check the reactions of the message
..
for guild permissions or channel
i can have multiple of those tasks at once right?
custom check π
@commands.has_guild_permissions(**args) @slate swan for guild perms..
he wants to have multiple options, that the invoker has either kick or ban perms
Ohh
how can I listen for messages only on a certain channel?
why not use check_any?
if message.channel.id == ...:
...
can u give example
@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if any of the checks passed will pass, i.e. using logical OR.
If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckAnyFailure "discord.ext.commands.CheckAnyFailure") is raised to signal the failure. It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Note
The `predicate` attribute for this function **is** a coroutine.
New in version 1.3.
oh wait my bad
bru
How do I delete message sent by user 5 seconds after it's sent?
command?
i dont see why not
or on_message
asyncio docs has no note saying you cant
how would I cancel one of those loops?
uh like this?
def givcheck():
pass
@commands.check_any(givcheck())
task = bot.loop.create_task(task)
task.stop()
?
@spring flax
no...
..
example pls?
oh it's a while True task...
here's an example```py
@bot.command()
@commands.check_any(commands.is_owner(), is_guild_owner())
!d asyncio.Task.cancel
cancel(msg=None)```
Request the Task to be cancelled.
This arranges for a [`CancelledError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.CancelledError "asyncio.CancelledError") exception to be thrown into the wrapped coroutine on the next cycle of the event loop.
The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a [`try`](https://docs.python.org/3/reference/compound_stmts.html#try) β¦ β¦ `except CancelledError` β¦ [`finally`](https://docs.python.org/3/reference/compound_stmts.html#finally) block. Therefore, unlike [`Future.cancel()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel "asyncio.Future.cancel"), [`Task.cancel()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel "asyncio.Task.cancel") does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged.
Changed in version 3.9: Added the *msg* parameter.
The following example illustrates how coroutines can intercept the cancellation request:
okay thanks π
how can i add permissions??
Would there be a better way than the one you gave me?
not that i can think of right now not really, dont take my word right now its 3:35 am and im tired so probably ask someone else
π
is message.content a string?
yes
Ok
!d discord.Message.content
The actual contents of the message.
you can check the return type in docs or src
@spring flax like this?
@commands.check_any(commands.has_permissions(),commands.has_permissions())
yeah
alr
obviously you have to put the permission to check for though
@commands.hybrid_command(description="Displays inspirational quotes.",
help="Gives an inspirational quote.")
async def quote(self, ctx):
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)[0]
embed=discord.Embed(title='Inspirational Quote', colour=0x2f3136,
description="β " + str(json_data['q']) + " β",
url="https://zenquotes.io/")
embed.set_footer(text='- ' + json_data['a'])
await ctx.reply(embed=embed)
why am i able to use this command only with prefix but not with slash
oksy so my bot gives output like this
how can i make it look like proper columns
this is a text but yeah i will embed it
And what is your code
oh just a sec
@client.command(name="moves")
async def moves(ctx: commands.Context, *, pokemon: str):
with open('moves.json') as json_file:
movedata = json.load(json_file)
pokemon_moves_list = movedata.get(f'{pokemon}')
if pokemon_moves_list:
pokemon_moves = ""
counter = 1
for i in pokemon_moves_list:
if counter % 3 == 0:
pokemon_moves += f"{i}\n"
counter = 1
else:
pokemon_moves += f"{i}\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
counter += 1
await ctx.send(pokemon_moves)```
ffs
what do i do then π
how do i divide the output into 3 fields
yeah
thats the question
how do i split it to three π
its one single string
oh sure
yeah its the list
one sec
anyone need help w/ how to read the contents of attachments (it is a skill a specialize in)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2
i got the gist but idk how exactly to do that
yeah i can find the length and divide it by three but what incase there are number of values which are not divisible by three
!e
your_list = ["Fly", "Roar", "Ice Beam", "Blizzard"]
print(len(your_list) // 3)```
@odd mango :white_check_mark: Your eval job has completed with return code 0.
1.3333333333333333
how do i deal with this ^^
ohh
!e
your_list = ["Fly", "Roar", "Ice Beam", "Blizzard"]
print(len(your_list) // 3)```
@odd mango :white_check_mark: Your eval job has completed with return code 0.
1
okay.. what next
also, i want only 30 values on page 1, similarly on page 2, and so on
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['Fly\nRoar', 'Ice Beam\nBlizzard', 'Hyper Beam\ntest']
LMAO i thought you will make 1 list into 3, but you.. YOU WHAT LOLL
man that's genius
actually, how about textwrap
okayy
ohh
How can I change server's banner?
!d discord.Guild.edit has that dunno?
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The rules\_channel and public\_updates\_channel keyword-only parameters were added.
Changed in version 2.0: The discovery\_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned...
yeah it does
Ty!
Hi, i am trying to make a bingo cmd where i am using a function winner as here:
https://gist.github.com/AmazingAkai/885c25d307149319a55654037b172c43
But the winner function always returns False ig there some part is wrong so i need help with that
hey quick question how do I get multiple button rows here is what i have so far
`buttons = [
create_button(style=ButtonStyle.grey, label="name"), create_button(style=ButtonStyle.grey, label="name"), create_button(style=ButtonStyle.grey, label="name"),
]
grid = create_actionrow(*buttons, )
await ctx.send(embed=TTT_Game, components=grid.get)`
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/client.py", line 393, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() takes 1 positional argument but 2 were given
@commands.Cog.listener()
async def on_message(message):
if message.content == "hello":
await message.channel.send(f"Hey {message.author.mention}! Whats up?")
```
i get ```py
sum_of_all = sum(product)
TypeError: 'int' object is not iterable
for this in an `on_reaction_add` event
```py
all_reactions = reaction.message.reactions
for idx, r in enumerate(all_reactions):
product = idx * r.count
sum_of_all = sum(product)
avg_rating = sum_of_all / sum(single_reaction.count for single_reaction in all_reactions)
print(avg_rating)
okay i got it down
can i use @commands.Cog.listener() 2-5 times in a cog ?
what's sum
you can use it infinite times
sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*βs items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").
Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
sum sums an iterable, product is int
would anyone happen to know?
but have you overwritten it
!e
a = [1, 2 ,3]
print(sum(a))
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
6
oh okay, what's the alternative?
i want to sum the product from each item in the lsit
from this ```py
for idx, r in enumerate(all_reactions):
product = idx * r.count
product * len(list) ??
@commands.Cog.listener()
async def on_message(self,message):
if message.content == "hello":
await message.channel.send(f"Hey {message.author.mention}! Whats up?")
await asyncio.sleep(2)
await message.channel.send(f"Hope you are Fine!, Aren't you?")
@commands.Cog.listener()
async def on_message(self,message):
if message.content == "happy birthday":
await message.channel.send(url='https://cdn.discordapp.com/attachments/969178492002500678/971014900723896320/unknown.png')
when i added this its not working and it shows this
no basically what I want is to get the overall rating out of 5 stars out of the reactions of a poll. So that won't work
because pyflakes doesn't know what dpy does
but what's the point of two on_messages
it doesn't make sense
both the commands r not working now wht to do ?
when it was in main.py it showed tht warning but it worked
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
lemme read the docs
did you load the cog?
yes it was working until i added this ```py
@commands.Cog.listener()
async def on_message(self,message):
if message.content == "happy birthday":
await message.channel.send(url='https://cdn.discordapp.com/attachments/969178492002500678/971014900723896320/unknown.png')
ok
lemme tp#bot-commands
@commands.command()
async def edonate(self, ctx, event, prize, *, msg):
embed1 = discord.Embed(title=f"{ctx.author.name} wants to make an event donation!", description=f" \n:dot_877959363388641300:**Event:** {event} \n:dot_877959363388641300:**Prize:** {prize} \n:dot_877959363388641300:**Message:** {msg}", color = discord.Colour.random())
embed1.set_author(name=ctx.guild.name)
embed1.set_footer(text=ctx.user.name, icon_url=ctx.author.avatar.url)
if msg == None:
await ctx.send("Please provide a msg, if the message is none use a **.**")
if prize == None:
await ctx.send("Please provide the prize for winner.")
async with ctx.typing():
await ctx.send(embed=embed1, view=Buttons())
buttons aren't sent
how do I use memberConverter in pycord?
any amount of times, although you can only have one on_message event listener
hmm, could u give an example?
i have some code that calculates the overall "rating" off of a poll's reaction count.
Now I want to reflect this overall rating in the form of stars, like in the image below.
How would I go around doing this?
oh I did that already thanks for the help though
command with 4 arguments is breaking my brain with if else statement
like number of upvotes/5 sort of thing right?
yeah
Not a big deal
this is a better example
u wanna look at it?
Ye?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
i imagine something like 50 upvoted and 7 downvoted? so u can just do upvotes/totalvotes
I have the code that gets me the overall. I just am not sure how to show it in the form of stars
oh u want the image as well
Nice
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
dont ask man π
x = [j+(30-len(j))*" " for i in [pokemon_moves_list[i: i+3] for i in range(0, len(pokemon_moves_list), 3)] for j in i]
y = [x[i: i+10] for i in range(0, len(x), 10)]
lemme tp again#bot-commands
i just wanna die after seeing that block
with a few modifications, i can now divide the embed into pages and use buttons to navigate
@slate swan it would be great if i could increase the distance between move names in horizontal manner
you got any clue how i can do that?
not fields, just a field
can we take this to dms if thats fine by you?
i can explain it better there
ah okay okay
i will just put it here
ughh ditch its too much to explain π
@slate swan do you know how to enter text in embed field name and not get it bold?
so I used @tasks.loop(minutes=1) . this sends every minute a message to a channel. how can I do it for multiple channels?
i am already making it empty
not possible
channels = [] # List of channels
for ch in channels:
await ch.send("a")
```but 1 min can ratelimit your bot from sending messages (potentially) so i dont recommend doing it
use a list of channel ids and for loop it
how do you tell if a message mentions the bot?
@client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
Now the problem is the kick and ban command doesn't work, except the other responds command
To handle your bot being mentioned in a message (commonly to respond with a prefix) you can do the following:-
import re
...
@bot.event
async def on_message(message: discord.Message) -> None:
if re.fullmatch(rf"<@!?{bot.user.id}>", message.content):
await message.channel.send(f"My prefix is `{some_prefix_here}`!")
return
await bot.process_commands(message)β
This will only work if the message is solely a mention, or it will process commands otherwise.
what doesnt work, any errors logged?
what about to see if it replies to the bot also
also thanks for responding
on the screenshot no red marks or something
do you have an error handler
wdym
check audit logs and see if the member got banned
if they did then it's not that the command didnt work, you just didnt send anything in chat to notify them the ban/kick went through
how do you check if a message is replying to something the bot said
I did "?kick [user] [reason]"
!d discord.Message.reference
i cant think of a simpler way rn but
ref = getattr(ctx.message.reference, 'resolved', None)
if ref and ref.author == bot.user:
# Replied to the bot
and by the way no banned users on the audit logs
just typed the command, nothing happened
do some debugging, try excepts ```py
try:
do stuff
except Exception as exc:
log error
okay i somehow managed to increase space, quick question
which interface looks better among these two:
okay!
so I did it like that now and the bot starts without errors but doesnt send messages
make sure you get channel
and not just put ids
how do you make the bot change its nickname in a server?
channels = ["channel-name"] like that?
how can i fix this guys
well not only ban or kick command doesn't work, but this code doesn't work too:
@client.command(pass_context=True)
async def addrole(ctx, member: discord.Member=None, *, role: discord.Role = None):
await client.add_roles(member, role
no errors showed up
outdated af, do you have any on_command_error event?
why are you calling function recursively ?
bad typehints
for member in members:
nope
this is what i learned π
oh its outdated?
why would you typehint an argument to discord.Client
channels = ['1234567890', '', '', ....] #list of channel ids
for ch in channels:
await client.get_channel(ch).send("a")```
to get the server members !
cause 3rd party librariy
how to get this lib
you still don't have client as an argument
its not type hinting ig π
!d discord.Guild.members
property members```
A list of members that belong to this guild.
so what to do to fix it ?
oh yeah, still server variable being a discord.Client is not fine
async def command(ctx):
server = ctx.guild
``` you can get all members using server.members
ok i'll try it
for members in ctx.guild.members:
ctx.send(member.name)
this... this code breaks every single pep that exists
pep 9001 is still valid
!pep 9001
PEP 9001 does not exist.
server = ctx.guild
await ctx.send (server.members)```
like this ?
it does exist
no
this will just send a list of all members in the server
you can simply do this
async def members (ctx)
for member in ctx.guild.members:
await ctx.send(member.name)
ok i'll try
Here is the log:
Number is 31
15
22
64
68
70
11
49
71
3
72
50
43
None
63
46
27
17
62
59
37
13
31
1
36
16
Why does this always return None
def get_number_coordinates(self, number: int):
print(f'Number is {number}')
for y in range(len(self.board)):
for x in range(len(self.board[y])):
board_number = getattr(self.board[y][x], "number", None)
print(board_number)
if board_number is None:
continue
else:
if board_number == number:
self.board_x = x
self.board_y = y
else:
continue
return self.board_x, self.board_y
Log given above
finally it works !!
even if there is 31
thank you so much bro
βοΈ.
Any help?
button class itself is not view instance ig
how does this work
Where do I learn to make Discord bots by python ?
you must define button inside view class instance and pass your instance to ctx.send(view=MyView())
there has to be a better way to see who is mentioned in a message then this
what experience do you have with python?
alright tell me the better way then π
class Buttons(discord.ui.View):
def __init__(self, *, timeout=60):
super().__init__(timeout=timeout)
@discord.ui.button(label="Denie",style = discord.ButtonStyle.red,emoji=":cross8:") # or .secondary/.grey
async def gray_button(self,interaction: Interaction, button: Button):
await interaction.response.send_message(f"Your donation has been denied by {interaction.user.mention}.")
@discord.ui.button(label="Hold",style = discord.ButtonStyle.gray,emoji=":load:") # or .secondary/.grey
async def gray_button(self,interaction: Interaction, button: Button):
await interaction.response.send_message("Your donation has been put on hold {interaction.user.mention}.")
@discord.ui.button(label="Accept",style = discord.ButtonStyle.green,emoji=":tick:") # or .secondary/.grey
async def gray_button(self,interaction: Interaction, button: Button):
await interaction.response.send_message("Your donation has been accepted by {interaction.user.mention}.")
if bot.user in message.mentions
there is message.mentions but idk how it works exactly
but this one needs Member intents, invalid-user's code will work without intents too so i'd go with regex too
thing is it wont work if you reply with pings off lmao
only basic
are you loading cogs after bot.run(token) ?
yes because thats not mentioning the person
i mean maybe inside on_ready() event listener
same goes for the code you sent? ( notice that that isnt the message.reference code)
Nope
yes
how do you check if a message is replying to something the bot said
"replying"
so first you said replying and now mentioning
i was talking about the reference code because they said they didnt wanna work with regex
no, first i said mentioning.
load them before bot.run
oh, they quoted the message in which you checked bot's mention using regex so....
sure
k
scroll up more bruh
Above bot.run right?
discord what is this
yeah like
bot.load_extension()
bot.run(token)
well thats weird
yea
i am using py-cord
well, new methods have been added to make it easier to use
its not the case with py-cord ig
use the setup_hook method
?
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
life saver 
oh sorry i forgot to reply to your message
you should be aware of basic asyncio, classes and functions before making a bot, are you?
@dapper tendon well if you are willing to stick by it
you will learn them along the way
but yeah it would be hard
and more time consuming too
nope, neither in any other forks
i had jumped straight to discord bots after learning functions loops and operators
might have had a hard time in the beginning?
yeah quit 3 time
I'm ready and I want to learn
lol
lol same, i started making bots without having knowledge of functions/keywords etc. i used to think async is some magical word that made this function a "bot function"
i had issues with variable scoping in the start, since i knew functions and classes but never actually worked with them..m
yeah but if i put it down
learning python would have not been fun without discord bots
i dont agree because i have different interests but i can see why
like ?
more into learning language in dept, i just made discord bots cuz my friends wanted something
python is used for more than ml and maths
and data science
python can be used for everything.
^^
u might need some other tools
thats technically true for most of the programing languages...
most of the general purpose programming language
u can anything with a turing complete machine :)
||I consider both equally bad but discord.py is better, a bit hard tho||
why don't u like dpy?
with discord.py ?
if i want to write a command that deletes all channels under a certain category id when i type a certain command word, is that something thats possible to do? i want to be able to delete all channels created by my game bot under x category but im unsure how to go about it
any major project
is there a delete all command that i can customize to fit my use?
Guys, how can i log someone name change ? (not a nickname)
delete category maybe if thats possible
the CommandTree class is absolute pain,
dpy is not really strict typed
and too much cache dependent
!d discord.on_member_update
slash commands are awful too
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
check for the name property
u guys want a old bot i made with the level system
with what in currently using, they are easier, gets registered faster ( due to new API ofc ) and can be intermixed with normal command
pain for sm1 who doesn't like decorators tho
same as mee6
π how customisable is it?
No documentation found for the requested symbol.
discord, disnake and nextcord are the current libs included
:o
why not py-cord
use data from sql server
most of the regulars here use disnake or nextcord as a fork so yeah
@unkempt canyon itself was being re-written in Disnake before dpy made a comeback
whats so bad about dpy
yeah
nothing ig?its not bad
what do the forks provide
easier slash commands interface
and pretty server icons
@slate swan u use mypy?
||and awesome devs like vco||
sometimes
easier than dpy2 hybrid commands?
but still i consider using strictly typed libraries even if im not
no forks have hybrid command yet? ( maybe enhanced dpy does)
that's a killer feature for me
Pycord had "bridge" commands that create a slash command and work as prefix commands
if that is what you mean by hybrid
hybrid_group and hybrid_command decorators that make either act as both
me casually using @lightbulb.implements() decorator, yeah
if before.name != after.name:
embed = discord.Embed(title = f"NΓ©v megvΓ‘ltoztatva {badge}", color = 0x66ffcc, timestamp = datetime.datetime.utcnow())
embed.add_field(name = "ElΕtte", value = before.display_name)
embed.add_field(name = "UtΓ‘na", value = after.display_name)
embed.set_footer(icon_url = after.avatar_url_as(size = 128), text=f"{after} β’ {after.id}")
embed.set_author(name=f"{after.display_name}", icon_url=after.avatar_url)
embed.set_thumbnail(url=after.avatar_url)
await a.send(embed = embed)
This log not work, why? <t:1654429830:R>
But then, not everyone uses hikari, sooo
why does my message object have no 'content' π’
they be missing lots of cool stuff
lightbulb is static as well?
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
β’ The message was sent by the client
β’ The message was sent in direct messages
β’ The message mentions the client
This applies to the following events...
anybody?
i gave it all intents
intents = discord.Intents().all()
client=discord.Client(intents=intents)
is that right?
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
most of the part yes, hikari natively is completely mypy compatible
nice, imma use hikari soon
seems like that, then those messages didn't have a content?
yea no content
anybody? ||(i wait for the answer timer: <t:-161274115554:R>)||
member intents?
intents = discord.Intents().all()
intents.members = True