#discord-bots
1 messages · Page 452 of 1
idk, most people try and check if any msg.content in word for idk like word filters
if you fetchone it only returns the row, if you fetchall it returns a tuple of all the rows selected, you need to make a for loop to iterate and then compare that
if word in content: do this
Ok
@fading mica
anyone know why im getting this error message?
edit to None
Oh okay. thanks
None is written with capital N in python
Fixed it, thanks though
bro me learning
how can i dump 2 channel ids in a json?
embedchannels = {"epicList": [embedchannel]}
with open("./botFiles/embedChannels.json", "w") as f:
json.dump(embedchannels, f) ```
this only dumps 1 id
Put 2 ids in embedchannel?
@waxen granite r u using json as a db?
yes
@waxen granite ah don't use it as a db
well i am tagging 2 channels in my command that saves those ids in a json. but it only saves the id of 1st tagged channel
How i can remove row in aiosqlite
its working for what i am using it. so...
Try printing embedchannel to see if there're actually 2 ids in the list
@slate swan use, DELETE
okay
@waxen granite json is not a db
Well, it works
Though it is not preferred
DELETE FROM table my_row
?
@slate swan wait lemme show u a example
oh ok. BTW Im using aiosqlite
@vagrant brookprint only 1
Can I see your full command
await cursor.execute(("DELETE FROM table_name WHERE your_args = ?"), (your_value,))
@slate swan ^
Oops there is a mistake
If I were you, I'd use commands.Greedy converter
hm
!d discord.ext.commands.Greedy
ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
btw i forgot but what does * depict?
!e
await cursor.execute(("DELETE FROM table_name WHERE your_args = ?"), (your_value,))
@hoary gust :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | SyntaxError: 'await' outside function
!e
cursor.execute(("DELETE FROM table_name WHERE your_args = ?"), (your_value,))
@hoary gust :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'cursor' is not defined
Well, in discord.py specifically, it tells the bot to take everything left into the argument behind the *
But that will work
async def setembedconverterchannels(self, ctx, channel: Greedy[discord.TextChannel]): like this?
Try it and see
greedy is not defined
You have to import it from discord.ext.commands
why would you even try to eval that

That works too
remember, it returns a list so you can't call .id on it
You have a list of TextChannel objects
Just loop over it and insert the IDs into a list ¯_(ツ)_/¯
This won't work on snekbox 
It's for simple evaluations
If I want to send an Attachment how can I? I tried .save but anyone know how to save it to the current dir?
You need to send or save?
await to_file(*, use_cached=False, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Converts the attachment into a [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").
New in version 1.3.
can u elaborate xd pls
like for embedchan in channel:
what next?
hi, idk why the game status thing doesn't work but console doesn't return any errors
import json
import os
import platform
import random
import sys
from discordTogether import DiscordTogether
import discord
from discord.ext import commands, tasks
from discord.ext.commands import Bot
client = commands.Bot(command_prefix="tost!")
togetherControl = DiscordTogether(client)
bot = Bot(command_prefix=["tost!"], intents=discord.Intents.default())
# Setup the game status task of the bot (hopefully)
@tasks.loop(minutes=1.0)
async def status_task():
statuses = ["with kittens", "with fire"]
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
you need to start the task function
no it's just in the main file
how 
use status_task.start() inside on_ready event
@bot.event
async def on_ready():
change_status.start()
print(f'logged in as {bot.user}')
like this
not necessary
thanks :D
ok
i can delete by word. Like !deleterow name
function?? 👀
You forget to add a function
add ()
@status_task.before_loop
async def whatever():
await blah()
who isnt xd
me extra noob 
ask them to help us then xd
Are just learning the basics will be enough to make py.bots?
bc i'm still learning python
lol
R u askin that how much python u need to know to start dpy?
how to get the channel id from a list of textchannel objects?
@tawdry perch
In the code you help me. I can do the opposite of that?
Like !deleteblword <name of bl word>
Well, it really depends tbh. I never learnt any Python before getting into bot making (I didn't even know how to call a function or what's the use of function)
But it's recommended you learn OOP and stuff
classes, objects and stuff
well try copying and understanding some commands, in a month you will be good to make some commands yourself
kek i fixed some stuff this should be good right?
@bot.event
async def on_ready():
change_status.start()
print(f'logged in as {bot.user}')
@tasks.loop(minutes=1.0)
async def status_task():
statuses = ["with kittens", "with fire", "krunker (not sponsored)"]
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
@status_task.before_loop
async def mrow():
await bot.wait_until_ready()
py is just coding in english
i wish i could code in martian tho it would be cool
ty bc I've just started learning py and i'm kinda lost I wanna make bots and web dev
xd
Ah best of luck!
text_channel.id
lol
use this attribute
.id
You can send docs or something?
TextChannel
docs for what?
that's an example
aiosqlite. For DELETE
oh
for chan in channel: chan = channel.id
like this?
sure
execute("DELETE FROM table_name WHERE put_your_conditions", (put_your_values))
@slate swan
oh
oh
would be better
Append the id into your list
oh thxx. I can delete by name? like !deleterow <name>
then do whatever you want to do
yep
like !delete something
its possible? @spring flax
delete the whole record?
yea

so you can use the format i gave above
oh
ok.
any1 knows how I can forward messages from my one channel to another? they changed the api I think
if i upload this it wont work right
should i just keep it prefixes.json to work cause i need to upload it in github
hyelp
can anyone tell how to check who is getting mentioned in a message ?
meant easy :3
than other langs
pls help me....
can anyone tell how to check who is getting mentioned in a message ?
SQL 
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
k thnx
but how to put it in my if statement ?!?
What is your if statement
@bot.event
async def on_message(message):
if message.mentions:
print('mention detected')
if f'@T3raStack#1234' in message.content:
await message.channel.send('The User is AFK')
so how do I do it ?
It's actually <@ID>
wait a sec
You can just check if the member is inside message.mentions
Since message.mentions already returns a list of members mentioned
wht do u mean ?
i did not understand
how do it check ?
@bot.event
async def on_message(message):
if message.mentions:
print('mention detected')
if f'@757279814360104980' in message.mention:
await message.channel.send('The User is AFK')
like this @vagrant brook ?
mentioned_in(message)```
Checks if the user is mentioned in the specified message.
ig that's better
lemme try
so instead of User, wht should i put to check if someone mentions me
get_user(id)```
Returns a user with the given ID.
put your id there, it returns a User object
oh thnx 🙂
whats the difference between bot.say vs channel.send
(:
Anyone know how to make an api request on start-up once?
on_ready event?
make a task and set the count to 1
Triggered more than once
Call multiple times per-session
I mean you can add a counter
Yeah I thought about it
That's the best bet
I'll just do that
hey
It does block I think
it is showing discord.client has no attribute 'get_user'
I just did something like:
already_loaded = False
if already_loaded:
return```
please learn oop
Should be your bot instance, not the class itself
i did
already
clearly didn't
wdym
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\Giang\AppData\Local\Programs\Python\Python38-32\lib\site-pac
i got this error on the first line:
import discord
reinstall discord.py ig
ok
!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.pydis.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.
then what should i use ?
bot.get_user() ??
whatever you named your Bot/Client instance
i used bot
still not working
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
Traceback (most recent call last):
File "main.py", line 12, in <module>
bot = commands.Bot(command_prefix='dc ',intents=True)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 98, in init
super().init(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1107, in init
super().init(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 248, in init
self._connection = self._get_state(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 265, in _get_state
Traceback (most recent call last):
File "main.py", line 12, in <module>
bot = commands.Bot(command_prefix='dc ',intents=True)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 98, in init
super().init(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1107, in init
super().init(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 248, in init
self._connection = self._get_state(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 265, in _get_state
Traceback (most recent call last):
File "main.py", line 12, in <module>
bot = commands.Bot(command_prefix='dc ',intents=True)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 98, in init
super().init(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1107, in init
super().init(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 248, in init
self._connection = self._get_state(**options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 265, in _get_state
return ConnectionState(dispatch=self.dispatch, handlers=self._handlers,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/state.py", line 152, in init
raise TypeError('intents parameter must be Intent not %r' % type(intents))
TypeError: intents parameter must be Intent not <class 'bool'>
wht is this error ?
first time encountering this
you have to pass in an instance of discord.Intents into the intents kwarg not a bool
do you guys know some free bot hosting service that i can use while testing my bot? the ones that i can upload files to it to run the bot
there are no free hosting services
is kinda good
thats not a hosting service
yea
wait, can you upload files there?
i think so
maybe ill use it
and then use another one when my bots done
bot = commands.Bot(command_prefix='dc ',intents=intents)
wht here ?
what
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
oh wait
i got it
but
wht is this ???
File "main.py", line 321, in on_message
if User.mentioned_in(message):
AttributeError: 'NoneType' object has no attribute 'mentioned_in'
in my code :
User = bot.get_user(757279814360104980)
User.mentioned_in(message)
@hasty iron
get_user looks it up in the cache, if the user is not in the cache it will return None
fetch_user will look it up using an API call
!d discord.Client.fetch_user
await fetch_user(user_id)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/stable/api.html#discord.User "discord.User") based on their ID. This can only be used by bot accounts. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.get_user "discord.Client.get_user") instead.
oh and for the user cache you need the members intent so if you don't have that the users cache will always be empty and get_user always returns None
!d discord.Guild.get_member_named
get_member_named(name)```
Returns the first member found that matches the name provided.
The name can have an optional discriminator argument, e.g. “Jake#0001” or “Jake” will both do the lookup. However the former will give a more precise result. Note that the discriminator must have all 4 digits for this to work.
If a nickname is passed, then it is looked up via the nickname. Note however, that a nickname + discriminator combo will not lookup the nickname but rather the username + discriminator combo due to nickname + discriminator not being unique.
If no member is found, `None` is returned.
that is getting the entire member
i have the member, i just want his entire username
i think member.name + member.discriminator does the work
me added 3 commands and all work dont make me meme
wtf is memeber
member
lol
typo
Xd
Member.name and member.discriminator
yeah ended up doing that i was looking a for a way without having to concatenate
str(member)
that will work?
why discrimination here bro we got it 100 years ago lol

for i in reversed(range(0, 9999999999999)):
print(i)
await asyncio.sleep(1)
how do i get guild from id
no guild from guild id
bot.get_guild(2738273823)
ok
idk what to put tho
new to coding
help
it not work
ohk
sorry
why is await ctx.message.delete() in a try block
lmao
where to put
it's never gonna fail, except when your bot doesn't have permissions
and why is there a ctx argument in send()
it should be only message
yes
@client.command()
async def say(ctx, *, args):
await ctx.send(f'{args}')```
ru trying to make a purger
no
i have command already
f sfring be like
f
lolsee wht abt try
remove those brackets
Indentation 
try this
5 space indents 
why is there a try execpts in a say command?
Ditttt forcing people to use their f-string obsession
Mind my grammar.
thnx it works

it works
no need for fstring
^
its already a string
why
huh
restart your bot
bro hosted on heroku
so two times 1 error
1 correct command


Just make a separate bot
for testing
or run it on your PC and disable heroku while testing
hi, can somebody explain me what a cog is? tenks
sorting code in different files so it's more readable
or organizing your code like bookmarks
see
String @slate swan
then wht to do
Please revise your python basics before using dpy
strings
k
Quotation marks
yeah, !resources should help
also just do case_insensitive=True where you defined client
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
yes very importatn got it
yes
something else cool to add is command_prefix = commands.when_mentioned_or("$") 
command_prefix = commands.when_mentioned_or("hello","Hello","HELLO")


ok tenks

jesus me internet
anyways, beat that

wait
that's the same as case_insensitive

wtf is the second one
it looks cool
I think it means if you mention the bot when using the command works also
Case insensitive makes commands case-in... not prefix iirc
!d discord.ext.commands.Bot.case_insensitive
Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
Yes
ohk
bruh
@boreal ravine
Or just dont use it?
whaii
I said I think
how do i make all of my bot's commands only work in servers and not in dms
well i does not work like that i guess
i dk
?
Built-in Checks for the commands extension of discord py - Checks.py
also status does not work in dms
can anyone tell how to make this better ?
await message.channel.send('@everyone')```
i wanna get the member's status
pls test my bot
its working in servers, just not in dms
pls help
how
client = commands.Bot(command_prefix="!")
what
can anyone tell how to make this better ?
await message.channel.send('@everyone')```
some on told me this is not the right way
its not a command
its an event
what are you trying to make
sorry
@valid patio what are u trying to make
i want it to actually make it so tht if i typr hello it shld say hello how are you in 2 messages
i got confused
very fastly
wdym 2 messages
You wanna fetch the users status?
tbh im having problems with events too my bot is just sending it twice
yea
can anyone help me ?
Indentation error lol
i got it
i can use it in the server but cant in dms
lol
its good
?
bro pls can u test me bot lol
@boreal ravine
How would I be able to make the bot count a specific word in the chat, and all times that word have been said already?
no?
bruh !d count
!words
lmao


can anyone tell how do i make the reply repeat 100 times ?
await message.channel.send('@everyone')```
whai
u want to repeat
uhh u cant
i want to troll my friends
u'll get ratelimited
no
😦
ur bot cant spam if it does it gets ratelimited by discord
ohk type sane content in starts with past in channel.send
its api abuse
.
This gives me bad expression
why you need to everyone 100 times
sorry
trolling he is
akshu could u help me with events
to troll my friends
Not sure if we can help you with trolling someone @valid patio
This is a help channel 
And a learning server
@client.event
async def on_message(message):
await client.process_commands(message)
if message.author == client.user:
return
elif "haha" in message.content or "HAHA" in message.content:
await message.channel.send("HAHAHHAHAHAHAHHAHAHFKJNRFRKJRNJWRNJKRNJRWJWRWJKWRNKJ")
return
elif message.content == "wot" or message.content == "what" or message.content == "shenme" or "?" in message.content:
await message.channel.send("wot?")
return
```so i have this
ok i want to know how to make the message repeat
but for the "HAHA" it always sends twice
but not for the "wot"
and for the wot i want it the message content to be exactly the stuff i stated in the elif statement
Should not be like that 
Do you have any more event or listener which listens to same word?
nope
only this
!d discord.Client.user
user```
Represents the connected client. `None` if not logged in.
await user.add_roles(role, reason=reason)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
```huh
Try to match id like message.author.id == client.user.id. I guess just comparing author and user compares the instances also
me?
yes
what does that do btw?
I mean it checks if they have te same id
discord/user.py lines 99 to 100
def __eq__(self, other: Any) -> bool:
return isinstance(other, _UserTag) and other.id == self.id```
it also checks instance, but both inherits from same class, so should not matter
Yeah
Can I directly shut down the bot with some command in the console?
Unhandled exception in internal background task 'change_status'. 2021-09-06T12:08:09.796783+00:00 app[worker.1]: Traceback (most recent call last): 2021-09-06T12:08:09.796830+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/tasks/__init__.py", line 101, in _loop 2021-09-06T12:08:09.796830+00:00 app[worker.1]: await self.coro(*args, **kwargs) 2021-09-06T12:08:09.796834+00:00 app[worker.1]: File "/app/emojitv1.py", line 68, in change_status 2021-09-06T12:08:09.796835+00:00 app[worker.1]: await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.listening, name=f"ethelp || ping: {round(bot.latency*1000)} ms")) 2021-09-06T12:08:09.796853+00:00 app[worker.1]: OverflowError: cannot convert float infinity to integer
any idea why this error happened?
this is the first time i saw this kind of error
Just Ctrl+C or whatever the exit command is 
what's the issue?
k
oh wait
Also it's the discord.message module not the message instance
you made another mistake
help
Uh will you share the code for change_presence part?
i can
And what are the output commands?
yup
Why th 4 pings 
I pinged them in reply not you 
async def change_status():
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,name=(choice(status))))
Output commands.. what?
me wanna help
@tasks.loop(seconds=10)
async def change_status():
ran = random.randint(1, 3)
if ran == 1:
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.listening, name=f"ethelp || Vote me "))
if ran == 2:
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.listening, name=f"ethelp || ping: {round(bot.latency*1000)} ms"))
if ran == 3:
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.listening, name="ethelp || Version 1.0"))```
I got confused, sorry
nvm i got a possible reason behind this error, the bot didn't get ack back
ohhhhhhhh
ty
i gtg now bye
how do i make all commands server only?
@slate swan Why are you pinging me on every message dude
no, I wanted to restart it 
meaning it ignores users in dms
Nitro ending soon, yep?


@commands.guild_only()

all commands not just 1
i don't know about that
!d discord.ext.commands.Bot.check
check(func)```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
this
Time to leave discord 
Yay I am almost finished making modmail I started like 4 hours ago
noo 
you too yep
I was just making it a few hours ago and realized some limitations in dpy, so I dumped the idea 
What kind of limitations?
dynamic_cooldown does not accept ctx but message
@client.event
async def on_message(message):
await client.process_commands(message)
if message.author.id == client.user.id:
return
elif "haha" in message.content or "HAHA" in message.content:
await message.channel.send("HAHAHHAHAHAHAHHAHAHFKJNRFRKJRNJWRNJKRNJRWJWRWJKWRNKJ")
return
elif message.content == "wot" or message.content == "what" or message.content == "shenme" or message.content == "shen me" or "?" in message.content:
await message.channel.send("wot?")
return
```uhh the "HAHA" is still sending twice :|
hmm
oh
sorry
see api abuse
get ready to get ratelimited
Keep pinging me
Make a selfbot to just ping me, okay?

@slate swan bruh
oh but i rmbed someone here said if i dont put that there'll be an error or smt
Doing it allows you to mention the bot and use command without using any prefix
will get ban
Yeah not putting it stops your command working, but just try for a min and comment out back
yes
okay ty
Waiting for every server to lose their boosts after 5 days 
yess me nitro going 7 days

Ye it's quite sad I was a mod in about a 300k server after all boosts go we may go back to level 2 it's disappointing thinking about the perks we lose
Like no vanity url like bruh



You know discord is planning to reduce no. of boosts required for levels?
ig
Yeah I heard
let's see...
189 boost currently
Yeah but its not confirmed right??
Same
make level 4!!
Not sure, but it's active in one of my server
It has around 28 boosts and vanity works fine
it's too low smh
Imagine getting 30 second unskippable ad while switching servers 
maybe like:
1: 2
2: 10
3: 50
4: 250
5: 1000
6. 10000
Idk
hm
👀
lmao 6 😂
lol
If you think about it discord gave around $1,000,000 worth of nitro to discord users
INSERT INTO nitro (id, duration, boosts) VALUES (650447110402998302, "3-year", 5000);
```better

Boost a server 5000 times and become owner as perks
which kretin would ender a duration as a string like that
that's like so annoying to deal with
We noob at sql Discord's extra advanced database
lol
when executing the command:
@bot.command()
async def youtube(ctx, *, search):
query_string = parse.urlencode({'search_query': search})
html_content = request.urlopen('http://www.youtube.com/results?' + query_string)
search_results = re.findall('href=\"\\/watch\\?v=(.{11})', html_content.read().decode())
# print(search_results)
await ctx.send( 'https://www.youtube.com/watch?v=' + search_results[0])
Me marca este error: await ctx.send( 'https://www.youtube.com/watch?v=' + search_results[0])
IndexError: list index out of range
Does anyone know what happens? 
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
search_results is an empty list
o, thanks
guys if i want to upload it on github then wht should be its name prefixes.json only?
YouTube has an api to search videos
yes but i think if its a music bot then probably leave it cause u saw wht happened to Groovy
@lament mesa
What do you mean?
github doesnt affect anything
but in my pc it take HIMUNOID/prefixes.json
for github wht will it take
github doesnt do anything to your files
so it should be prefixes.json only right
i should name it
Its a place to deploy your code.
but my bot did not run when i first used HIMUNOID/prefixes.json
i host it on heroku
oh
deploy your projects and hope that it will become famous
private repository
pls help @hasty iron
i never used heroku with gh
Use relative path
./prefixes.json or somethin like that
heroku/any host won't have the root directory name same as your pc, so using relative path is always good
Can't think about a reason why you would use an absolute path
Just archived my gh's biggest repo 
guess
but why though?
wht u use
yes
i dont make bots anymore
Discord API is boring now
I'll find something else to work now
Also that repo is kinda unstable
so archived
Relatable.
py bots are dying rn anyways.
TypeError: 'in <string>' requires string as left operand, not tuple
There do be a lot of forks
I found it too much, too many forks n stuff. So just gonna move lol
To another language?
to hikari
I dont have the patience for another language, besides my packages do be py haha
Oh yeah..
@tawdry perch
There's a lot of forks that it's confusing which to use and which to trust that it'll receive updates for long time 
It'd be better if Danny didn't allow people making forks lol 
oof. Ok
Traceback (most recent call last):
File "main.py", line 38, in <module>
client = commands.Bot(command_prefix='!')
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
@slate swan code?
u can see it
I’m getting some error if anyone can help. Below is the code. ```@bot.event
async def on_command_error(ctx, error):
channel = ctx.message.channel.send
if isinstance(error, commands.MissingRequiredArgument):
await send_cmd_help(ctx)
elif isinstance(error, commands.BadArgument):
await send_cmd_help(ctx)
elif isinstance(error, commands.CommandInvokeError):
output.error("Exception in command '{}', {}".format(ctx.command.qualified_name, error.original))
oneliner = "Error in command '{}' - {}: {}\nIf this issue persists, Please report it in the support server.".format(
ctx.command.qualified_name, type(error.original).name, str(error.original))
await ctx.send(channel, oneliner)
And this is the error
in on_command_error
await ctx.send(channel, oneliner)
TypeError: send() takes from 1 to 2 positional arguments but 3 were given
send only takes content as positional arg
do await ctx.send(f"{channel}, {oneliner}")
Thank you that worked. Now I’m getting another error.
Exception in command 'help', 'set' object has no attribute 'keys'
¯_(ツ)_/¯
Lol. I’ll figure it out
On my code that I’m trying to solve?
no
Ahhh my bad
In webhook_id: Value "etKD7gAZGYhmYj-Gx-Ld20jk-tbHroKAvcK-APHBzYFp" is not snowflake.
what do i enter
for bot.fetch_webhook
this is not the full webhook btw
probably hard cuz you don’t know the language
yeah
but just asking, is it necessary to move rn?
import discord
from discord.ext import commands
class Errors():
async def errors(self, error, ctx):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title="Failed to run the command!", description="```py\nThis command is on cooldown. Please try again after {round(error.retry_after, 1)} seconds.```")
elif isinstance(error, commands.MissingPermissions):
em = discord.Embed(title="Failed to run the command!", description="```py\nYou dont have permission to run this command```")
elif isinstance(error, commands.MissingRequiredArgument):
em = discord.Embed(title="Failed to run the command!", description=f"```py\{error.param} argument is requierd```")
elif isinstance(error, commands.CommandNotFound):
em = discord.Embed(title="Failed to run the command!", description=f"```py\Command not found!```")
else:
em = discord.Embed(title="Failed to run the command!", description=f"Oh no! Something went wrong while running the command!")
await ctx.send(embed=em)
I have this class
And im importing it like from utils.errors import *
But it doesnt work..
Any solution?
@client.command()
@commands.is_nsfw()
async def nsfw(ctx):
embed = discord.Embed(title="I got some NSFW for you")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)``` can anyone help me make this say "i cant send nsfw in general channels " if the channel has no nsfw perms ?
if your bot isn’t verified, nothing will happen to it
ah
to verify it needs to be in 100 servers, correct?
@hasty ironcan y help me
add an if statement that checks if the channel is nsfw, and then put the part that sends the reddit link inside that if statement. then in the else statement, do
ctx.send("I cant send nsfw in general channels")
@slate swan this should help:
https://discordpy.readthedocs.io/en/stable/api.html?highlight=nsfw#discord.CategoryChannel.is_nsfw
guys
why does my webhook raise this error
webhook = await self.bot.fetch_webhook('id')
File "/home/caeden/.local/lib/python3.9/site-packages/discord/client.py", line 1493, in fetch_webhook
data = await self.http.get_webhook(webhook_id)
File "/home/caeden/.local/lib/python3.9/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
@hasty iron i beggeth of thy
how do you add perms to a webhook
lmfao
how can i make a command which shows all the guilds that the bot is in?
can i check a member has a role mid code? so not with the decorator
and can it be restricted to only certain accounts? im not referring to roles, or perms, just accounts
afaik you cant. what kind of command are you making?
i presume for guild in bot.guilds:
no thats a shitty way to do it
just do {len(bot.guilds)}
adding data to a db if they have a specific role
what are u using sqlite3
I may be wrong but you would need to put it to the everyone role...
@everyone role
how so? wdym
@wanton pebble it does but it will take it much longer
i still have to study about databases, but idk why u'd want to check for the role mid-command. do it at the start
if ROLE_ID in [role.id for role in member.roles]:
what permission does the webhook need?
thank you
just add them
no clue, never used webhooks
same...
Like I said, the permission that the bot is missing, probably needs to be given to the @everyone role.
what are webhooks used for anyway?
also, can someone help me wih the guilds command? how would the code be structured?
my bot isnt in the server where the webhook is in - it doesnt need to be in the server so that wouldnt make a difference...?
You leaked your webhook token? 
i removed half of it
how do i use it though
iirc the webhook gains the permission that you give to the @everyone role.
If you want the webhook to manage messages for example, the @everyone role needs that permission.
im trying to send a message to it
!d discord.AsyncWebhookAdapter
!d discord.Webhook.from_url
classmethod from_url(url, *, adapter)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Webhook "discord.Webhook") from a webhook URL.
use this
i did
async with ClientSession() as session:
webhook = discord.Webhook.from_url('https://discord.com/api/webhooks/blahblah', adapter=discord.AsyncWebhookAdapter(session))
but it says ```py
File "/home/caeden/.local/lib/python3.9/site-packages/discord/webhook.py", line 221, in request
async with self.session.request(verb, url, headers=headers, data=data) as r:
File "/home/caeden/.local/lib/python3.9/site-packages/aiohttp/client.py", line 1117, in aenter
self._resp = await self._coro
File "/home/caeden/.local/lib/python3.9/site-packages/aiohttp/client.py", line 381, in _request
raise RuntimeError("Session is closed")
RuntimeError: Session is closed
in what server?
what do you mean?
Any more code after it?
oh i think i might understand
yeah
@commands.Cog.listener('on_message')
async def send_to_channel(self, msg):
if msg.channel.id != idkwhyblanked:
return
async with ClientSession() as session:
webhook = discord.Webhook.from_url('https://discord.com/api/webhooks/uh', adapter=discord.AsyncWebhookAdapter(session))
embeds = msg.embeds
files = msg.attachments
file_list = []
if embeds:
await webhook.send(msg.content, username=msg.author.name, avatar_url=msg.author.avatar_url, embeds=embeds, allowed_mentions=discord.AllowedMentions(roles=False, users=False, everyone=False))
if files:
for attachment in files:
await attachment.save(f'./dicts/{attachment}')
file_list.append(discord.File(f"./dicts/{attachment}"))
await webhook.send(msg.content, username=msg.author.name, avatar_url=msg.author.avatar_url, files=files, allowed_mentions=discord.AllowedMentions(roles=False, users=False, everyone=False))
await webhook.send(msg.content, username=msg.author.name, avatar_url=msg.author.avatar_url, allowed_mentions=discord.AllowedMentions(roles=False, users=False, everyone=False))
Yeah your session got closed as you exited context
how do i keep it open?
either do this all in async with ... line, or make session like ```py
session = ClientSession()
do stuff...
session.close()
!d discord.Client.fetch_webhook will make stuff more easier
await fetch_webhook(webhook_id)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Webhook "discord.Webhook") with the specified ID.
i tried this but it said missing access when i tried to send a message :/
.
Your bot don't have manage_webhooks ig
my bot isnt in the server...
👀
it doesnt need to be in the server for a webhook
I think fetch should not work if you don't share any server
since webhooks also has a token
but you're getting it with only id
okay so fetch wont work? i have to use session?
means you need more perms to fetch it
^
@client.command()
@commands.is_nsfw()
async def nsfw(ctx):
embed = discord.Embed(title="I got some NSFW for you")
async with aiohttp.ClientSession() as cs:
async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
res = await r.json()
embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
await ctx.send(embed=embed)```
can anyone help me make this say "i cant send nsfw in general channels " if the channel has no nsfw perms ?
try if ctx.channel.is_nsfw()
oh what

pls help how do i make the bot list all the guilds that its in
is_nsfw()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is NSFW.
is that what you wanted?
i gave yu a link to the docs
@spring flax don't use ()
which refer to the nsfw thing
it doesn't work with them
!d discord.ext.commands.Bot.guilds
guilds```
The guilds that the connected client is a member of.
bot.guilds
Guys is it preferred to use MySQL for bot
Uhm well it depends
The database good for you depends on how you use it and how big your bot is
I like to use MongoDB most of the time. I recommend you try it, it's really good.
Will it be able to store so much data of around 100 users in sec and make 300-400 reads per second
@dapper cobalt I have tried mongo and it's slow
Not suitable for a bot
Seriously, slow?!
what kind of bots needs 400 reads per second

@slate swan Well I got this in my case and found that SQL are faster than mongo
Hmm..
A google search says 1,045 inserts per second
@lament mesa for what?
mongo
It's probably because of the distance between your cluster's location and where your bot is hosted. My bot is hosted in the US and my cluster is also in the US.
#include <iostream>
using std::cout;
int main()
{
std::cout << "Gay";
}```
And I need recommendations for SQL
Wrong server.
Uh that isn't python lmao
yes
Looks like c
its c++
Ah
okay, but this channel is for discord bot development using python
Guys what SQL db is preferred for a bot
just go to #c-extensions @rancid mirage and consider checking the pins
uh okay..
Anyone???
lmao python basics are so ez
Postgresql
i learned all the basics in 3 hours
okay.. good for you?
while in c++ it took me some days
How is it's read speed?
oh
thanks
then replace it with what?
its good
!decorators
Decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
• Corey Schafer's video on decorators
• Real python article
I need around 50-100 reads per second so it preferred to use PostgreSQL@spring flax
@static patio actually it'll be @client.command() in your case
since you defined commands.Bot as client
it is an event and not a command
yes, but instead of using the on_message event to check for messages that start with your prefix, you can make it a command
so i tried to make the guilds function, and i get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: add_field() missing 1 required positional argument: 'self'
this is my code:
@commands.command()
@commands.has_permissions(administrator = True)
async def guilds(self, ctx):
embed = discord.Embed.add_field(name="Server Count", value=len(self.client.guilds), inline=True)```
you need to instantiate it by calling discord.Embed, discord.Embed().add_field(...)
the inline thing is out of the embed cuz of discord's code formatting
ahh okay
oh
what do i put for create_category parameters if i dont want anyone to be able to access the channels inside it
i think you'd have to make it first then change permissions
find the role you want allowed, and set it so that role has read_messages and send_messages or whatever you want
it's a decorator
here
k
what's overwrites for in the params
you don't have to overrite
did you do that..?
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/stable/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
ty

Lol
Hey if I wanted to send a message when a command is used to a channel, how would I go about doing it
Log channel
so if this message intends come can i still use my bot (not verified) normally how i use now????
How can I make a list in an embed? for instance:
~ Server: [server name]
~ Owner: [owner's name]
Etc... I explain?
pls ans
Discord Developer
The guild name.
!d discord.Guild.owner
owner```
The member that owns the guild.
yea but how
!d discord.Guild.member_count
member_count```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Select the Bot scope and select the permissions after that. Then copy the link
illehgal
i realized you can mix js and py together
why would you want to
Indeed
I use python for frontend
Brython

But it compiles to js....
Add field
how can i get a list of all user IDs who reacted with ⬇️
Hwo do i put channel permissions in a if before and after statement?
wdym?
I am trying to get permission updates in on_guild_channel_update
what permissions would the bot need to execute this command:
@commands.command(name = "refresh", description = "refreshes the member and boost counts")
@commands.is_owner()
async def refresh(self, ctx):
guild = ctx.guild
members = guild.get_channel(884459371046768660)
boosts = guild.get_channel(749371688822767666)
await members.edit(name = f"Members: {guild.member_count}")
await boosts.edit(name = f"Boosts: {guild.premium_subscription_count}")
await ctx.send("updated stats")
manage channels and send messages
just manage channels?
So i gues it has to be done like if before.managemessageperm != After.managemessageperm: Await channel.send()
I dont know what this if statement be
hm so you want to just get info for when a channel is updated?
why use an if statement for that, cant u just use an event?
is Forbidden thrown when the command invoker doesnt have permissions or the bot doesnt have permissons
you can pong me idm
idm?
i dont mind
oh ok, I'll keep that in mind 
I have an error handler but only the error: CommandNotFound respones
how do i get the guild names? i had my code first print out the server names, and when it worked, i changed it into an embed. but now, it doesnt work. it just sends 4 seperate embeds, which have the number of letters in the name of the server. how do i make it send the server names, and also send everything in 1 message? this is my code:
@commands.command()
@commands.has_permissions(administrator = True)
async def guilds(self, ctx):
async for guild in self.client.fetch_guilds(limit=150):
embed = discord.Embed().add_field(name="Server Names", value=len(guild.name), inline=True)
await ctx.send(embed=embed)```
ignore the inline thing outside the command. thats just discord's formatting
will it work if i change the len thing
why are fetching guilds
so ik whats causing it to send numbers
just iterate through self.client.guilds
and its pretty obvious whats causing it to send numbers
you have len
also the limit of fields is 25, so it wouldn't work with 150
Why are you creating an embed and sending it for each guild?
ik, i didn notice that, i just changed my code which was printing the amount of servers the bot is in lol
but now it still send seperate messages
Because you are creating an embed for each guild.
so shud i remove the add_field?
@commands.command()
@commands.has_permissions(administrator = True)
async def guilds(self, ctx):
names = []
for guild in self.client.guilds:
names.append(guild.name)
embed = discord.Embed(description="\n".join(names))
await ctx.send(embed=embed)
client.guilds doesnt return an async iterator
i'll try that, thanks
I didn't mean to put that async there, my bad.
hs_class = str(usr.public_flags.all()).replace('[<UserFlags.', '').replace(
'>]', '').replace('_', ' ').replace(':', '').replace('>', '').title()
hs_class = ''.join([i for i in hs_class if not i.isdigit()])
hs_final = hs_class.replace(",", "").replace(
" <Userflags.Early", "").replace("Supporter", "")
es_brilliance = str(usr.public_flags.all()).replace('[<UserFlags.', '').replace('hypesquad_brilliance', '').replace(
'[', '').replace(':', '').replace('>,', '').replace('<', '').replace('UserFlags.', '').replace('>]', '').replace('_', ' ').title()
es_brilliance = ''.join([i for i in es_brilliance if not i.isdigit()])
def houseCheck():
if hs_final.strip() == 'Hypesquad Balance':
return f"{emojis.hs_balance}"
elif hs_final.strip() == 'Hypesquad Brilliance':
return f"{emojis.hs_brilliance}"
elif hs_final.strip() == 'Hypsquad Bravery':
return f"{emojis.hs_bravery}"
else:
return ''
def earlySupporter():
if es_brilliance.strip() == 'Early Supporter':
return f"{emojis.early_supporter}"
else:
return ''
def boosterCheck():
if user.premium_since != None:
return f"{emojis.nitro_booster}"
else:
return ''```
someone please show me a better way of checking user badges, these are for boosting and hype squad
bravery doesnt even work for some reason so this needs to be improved
tysm, it works now!
how can i get discord.Reaction object of all the reactions of this message?
channel = ctx.guild.get_channel(884430255681589279)
msg = await channel.fetch_message(884469364814925824)
!d discord.PublicUserFlags you can do usr.public_flags.early_supporter and if they have it, it will return True.
class discord.PublicUserFlags```
Wraps up the Discord User Public flags.
`x == y` Checks if two PublicUserFlags are equal.
`x != y` Checks if two PublicUserFlags are not equal.
`hash(x)` Return the flag’s hash.
`iter(x)` Returns an iterator of `(name, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 1.4.
wtf
:>
what about everything else
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
It's for all flags.
!d discord.PublicUserFlags
class discord.PublicUserFlags```
Wraps up the Discord User Public flags.
`x == y` Checks if two PublicUserFlags are equal.
`x != y` Checks if two PublicUserFlags are not equal.
`hash(x)` Return the flag’s hash.
`iter(x)` Returns an iterator of `(name, value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 1.4.
i think that only returns all the reactions, i want all the ppl who reacted with a specific reaction (hence why i need discord.Reaction)
ah okay
!d discord.Reaction.emoji you can check what the emoji is.
The reaction emoji. May be a custom emoji, or a unicode emoji.
oh also
https://github.com/Motzumoto/AGB-OpenSource/blob/df2c3f7e99ac9dc8fab64b5cdc11c21609c0e081/Cogs/guild.py#L512
if you wanna check out everything, agb is open source now (if you see anything that should be hidden pls let me know)
Cogs/guild.py line 512
async def user(self, ctx, user: Union[discord.Member, discord.User] = None):```
is this toggleable
I'm getting a Forbidden error for this code:
...
async def refresh(self, ctx):
guild = ctx.guild
members = guild.get_channel(884459371046768660)
boosts = guild.get_channel(749371688822767666)
await members.edit(name = f"Members: {guild.member_count}")
await boosts.edit(name = f"Boosts: {guild.premium_subscription_count}")
await ctx.send("updated stats")
The bot doesn't have permissions to edit the channels.
yes it does
forbidden is thrown if the user doesnt have permissions anyway, which i do
Forbidden is thrown when the action cant be completed
It happens in a commands.Cog.listener()
not really.
"Exception that’s thrown for when status code 403 occurs.
Subclass of HTTPException"







