#discord-bots
1 messages · Page 608 of 1
member.guild.get_channel
ok and
what and
what after that
get the channel you want by the id then use the async send method to send messages
!d discord.Member.guild
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
i dont get it can you type the code pls
i am noob i need someone to guide me
No that's spoonfeeding
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
You're never gonna learn if u ask for raw code
Wut
ok yes i got it
thanks i got it
thanks @sullen shoal

very bad
Deadly bad
even more bad than freecodecamp
You really have something against him dont you 😭
@commands.command()
async def test(self, ctx, amount:int=None):
for each in range(0, amount):
await ctx.send("testing")
how do i make it so after every message sent the bot will wait about 0.75 - 1 second to send the next message?
Async io
asyncio.sleep()
ok i will change it rn
import asyncio
print(a)
await asyncio.sleep(1)
print(b)
I think its like that
@quick gust sorry for the ping but the delay is a int right
yes int
time.sleep() takes a float
1.0 float and int 1 is same both can be used
Sued 
lol
I think it only takes ints
And not floats
time.sleep?
Wait nvm
it take both int and float
Yeah nvm
it accepts float but int 1 can be converted to 1.0 so yeah
Does asyncio.sleep() need await kinda forgot
I think yeah
Can I combine disnake with discord.py
yes i think
Cause its a coro
theres no need to do
yes it needs to be awaited
Yeah cause its a coro
You mean import disnake as dpy?
yea
just replace discord with disnake, disnake isnt as dumb as pycord to change discord.ext.commands.Bot to pycord.Bot
yeah it will
I saw it on stackoverflow a while ago so idk if it was outdated
kay,let me try
Tnx Very Much @sullen shoal @slate swan
Happy to help
its a feature of python so its gonna work
Yeah but i thought it was a 2.0 thing
you could do import discord as disnake as well 
Any module
import Myxi as poopyhead
that would work great
Ok this is getting ot so back to topic
lol
Idk why you would😭
Basically downgrading
?
How to set link - "Click here" in embed
no they are asking for hyperlink I think
no in embed blue colour
No a link with text
Anyone know how to split embed?
Like text thats a link
hyperlink
Yeah how to make that
Didnt know the term
ohk
fair
yeah
checks
nope
I think its checks idrk
yes checks
Why is that so?
Forgot what lambda mean
anonymous functions
m being the context?
message
Ah
i think its ctx tho not sure
doesn't works gibe example
doesn't checks only take a ctx object
i think its message
!e
print('hi' in ('hello', 'hi'))
Checks i think is for like more stuff cause your just checking a id
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
True
Well , is the command like for only the bot owner?
the callable is meant to be a predicate
if it returns True, it will invoke the command
@is_owner()
if you add an owner_ids= [ id1 , id2] in Bot
commands.is_owner()
si
habit idk
Bro what😭
kekw
yes
something's wrong with your prefix , show the commands.Bot var pls
it's @commands.is_owner() and is used above commands just like the @bot.command() VARIABLE
( sorry for the cap it was an autocorrect)
bare except bad
Yes.
That's not what I'm talking about , your command_prefix in commands.Bot @slate swan
Click here for item info isn't working
@commands.is_owner()
And thats not the bots var
Yes. Do that to every command
Or make a global check
@sullen shoal told you already
!d discord.ext.commands.Bot.add_check
.
add_check(func, *, call_once=False)```
Adds a global check to the bot.
This is the non-decorator interface to [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check "discord.ext.commands.Bot.check") and [`check_once()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.check_once "discord.ext.commands.Bot.check_once").
!d discord.ext.commands.check_any
@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/master/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/master/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/master/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.
I didn't saw
when we type "I am something" carl bot replies "I am Carl" i want this kind of a commamd
how do i do this?
Basic dpy
on_message
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
in this bot system of custom prefixes
Which is somehow wrong , show it
:(
You're cool , chill
use in statement
he is asking for this thing
Thats only if hes trying to search for a keyword which i doubt
Visual Studio or Replit
Vsc
Vsc 2021 or 2022
2048
how do i host it 24/7 with vsc?
You cant
2077
if i understood their problem correctly it will work if you do
if "I am" in content:
reply("im carl")```
then how
\
I think you have to add message.content
yeah
yeah just rough example
Vps
???
ok im gonna give him the exact spoonfeed wait a sec
Virtual private server
I should code it on Vsc and host it with replit
if "I am" in message.content:
await ctx.send("And i am carl")```
How do i make it lel Is it free
spoonfed
Theres free options but their all horrible
Ok mr.cool
replit then
is it fine?
dont call the message.content property
the returned value is None due to some reason
so what should i add?
remove ()
or just use listen()
Bad but its your choice
wait help me i will code it on vsc but how do i host it
also you have to process the commands on global on message event
can someone pls help in thi
which i forgot how to, maybe it was bot.process_commands()
Why in line 15 timeout is int
or smth
@surreal dust this was for you
.
also remove it from message.content
ok
It has to be a int not the literal type
what free options
okay
Not gonna recommend they all have their downsides
if i remove the brackets its showing an error
some webservers/hosting services besides replit and heroku , they are risky tho
They have acess to your code , thus your token :)
Not the best security wise
if you typehint it to int, the library will try to convert the argument to an int then pass it to the function which is the command (discord api sends the content as string)
Yea token leak issues and stuff
No i am asking i will use VSC for coding is there a site just to host
No its on_message(message)
One Time
okay
Check pins , you'd find some good ones
Uptime Robot?
Yeah ik but your supposed to add a actual int
i use keep alive py
and flask to host it
That's not a host
Yeah
ahhhhh i am not able to do it
Its just a site which keeps sending requests to your repl
And keep it online
Bro why does everyone ask if vsc can host 24/7 and then say replit better 😭
yes i just want to keep it online 24/7
can you pls help me fix this code
if you add int there, it will call int(arg) then pass it to the function. i think you're confused with default value and typehint
@client.event()
async def on_message():
if "I am" in message.content:
await channel.send("I am UwU-BOT")
Ah i get it now lmao
indent
hm if you want to at your risk , somehost or bot-hosting.net i would suggest
ah ok
Param
And its client.event
Remove the () from event and pass in a message in on_message
what message?
Message variable .
And change your bot instance from client to bot its bad practice
ok doing that rn
done
instead of game?
show updated code
or where?
@bot.event
async def on_message(message):
if "I am" in message.content:
await channel.send("I am UwU-BOT")
this is the code now and it doesnt work
hii how can we add animated stickers like this in embed
i suppose they are
Yeah it isnt
look
whats wrong in the indents?
i saw the error there
Its await message.channel.send()
discord.channel has no attribute send
ohh ok
<a:emoji_name:emoji_id>
!d discord.Client.get_emoji or just use the emoji object
get_emoji(id, /)```
Returns an emoji with the given ID.
add the emote to your server, then do \:emojiname: and copy what it sends and add it to your embe
just add this in embed?
Because if its a custom emoji it needs the id
oh
Yes replace emoji_name and emoji_id with the whatever u need tho
if you type \:kekw: you will get the id and the name seperated by a :
so custom emojis will work?
try it
it works but when i write I am this he starts spamming so hard
Where?
ok
Ofcourse
thank u
Never knew
in a discord server, for custom emojis
Instead of .event , it was for fortheping tho
how do i stop himm
snipe_message_author = []
snipe_message_content = []
@commands.Cog.listener()
async def on_message_delete(self, message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await asyncio.sleep(60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@commands.command(aliases=['s'])
async def snipe(self, ctx):
channel = ctx.channel
try:
e = discord.Embed(
timestamp=datetime.utcnow(),
title=f"{snipe_message_author[channel.id]}",
description=snipe_message_content[channel.id],
color=0x9641EA
)
e.set_thumbnail(url=snipe_message_author[channel.id])
await ctx.send(embed=e)
except:
e = discord.Embed(
color=0x9641EA,
description="No messages have been deleted"
)
await ctx.send(embed=e)
Problem: It keeps sending the except message whenever something has been deleted.
Not the deleted message, code gives no errors or warnings. I don't get any errors either.
if you dont have nitro, you may get the emoji link and the filename will be the id
Replit>VSc
lol
nu
my bot is spamming help
JK
what a sin
Gotcha
stop the bot?
Stop the code
i only want him to say I am UWU once
@surreal dust you need to make a check
Lmk if you know
Your bot is getting triggered by its own messages bet
check if message.author.bot is True
bot.listen?
if yes, ignore it (return)
yes got it
Yea , bot.listen()
can we still use discord.py module?
Yes
for now, yes
for now
snipe_message_author = []
snipe_message_content = []
@commands.Cog.listener()
async def on_message_delete(self, message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await asyncio.sleep(60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@commands.command(aliases=['s'])
async def snipe(self, ctx):
channel = ctx.channel
try:
e = discord.Embed(
timestamp=datetime.utcnow(),
title=f"{snipe_message_author[channel.id]}",
description=snipe_message_content[channel.id],
color=0x9641EA
)
e.set_thumbnail(url=snipe_message_author[channel.id])
await ctx.send(embed=e)
except:
e = discord.Embed(
color=0x9641EA,
description="No messages have been deleted"
)
await ctx.send(embed=e)
Problem: It keeps sending the except message whenever something has been deleted.
Not the deleted message, code gives no errors or warnings. I don't get any errors either.
I had a stroke
wait 2 more minutes and this guy will say "discord > vsc"
np
sherlock has been doing very random stuff lately
LOL
Yeah
Discord>VSC
Hes bored leave him alone
Not even 2 minutes, nice
well i am going crazy i had an exam
lol it fixed my bot got kicked from 3 servers
You need to leave
due to intensive spam
Leave>Dicord
how do i set case sensitivity to false
is this correct, its not coming as sticker, i dont ave this sticken in server so it coz of that
That was for some other person...
case_insensitive=True
@bot.event
async def on_message(message):
if "I am" in message.content and message.author.bot == False:
await message.channel.send("I am UwU-BOT")
Bro you can't compare that its too good😭
Yea correct, can the bot see the emoji?
in this code
pls help uwu thx cuz
with the id?
yes
Remove except and try to get the actual error
id also there
How did your copy the emoji I'd?
No not in a function
!d py str.lower()
Cyberpunk>VSC
what
use the lower() string method
i need to set case sens to flase in this code
what was not understandable in the statment?
^
but what for me?
okok
Sherlock>Me
with owo bot, i did owo emoji and it gives id
Dead Me
I see , is the bot in the server the emoji is from?
actually it was the problem and that is wat i meant to ask
Mhm so it won't be working without sharing a guild the emoji is from
!e
print('hello' == 'HEllO'.lower())```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
True
ok thanks one minute
Its 4am for me gn guys
Shut it
str("I am" == "i AM".lower)

this way right?
no need to call str and lower needs to be called
also in music part, in 'nowplaying' is there a method to get how much part it played ( 0:12/duration)
okay
Oh so based on your code , it must be because the value of str(message.guild.id) is set to null in the json , can your please check it
ok so Sarthak. the base of my code was this:
snipe_message_author = {}
snipe_message_content = {}
@client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await sleep(60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@client.command()
async def snipe(ctx):
channel = ctx.channel
try:
snipeEmbed = discord.Embed(title=f"Last deleted message in #{channel.name}", description = snipe_message_content[channel.id])
snipeEmbed.set_footer(text=f"Deleted by {snipe_message_author[channel.id]}")
await ctx.send(embed = snipeEmbed)
except:
await ctx.send(f"There are no deleted messages in #{channel.name}")
And when I made that into a cog file command it worked, im just confused on why it doesn't work now when I used the same things just in different spots
json as db bad
should i drop the code in the json file?
you had the above to variables = [] earlier xd
try using it now
ohhh
sorry
open the json and check the value from prefix
yeah but if i do it with {} it doesnt send an error or the sniped message
No message s at all?
and this code works, but the first code i sent didnt, for some reason
with this one? nope
cus this is the one im tryna use
even if i change [] to {}
it doesnt do anything
yea the list one won't work , it needs to be a dictionary
didnt work
so i need to use {}
i need help pls
cus if so, i thought as much
but then it still wont sent anything
well it still sends the last message, the "No message have been deleted" message
Add a {} in the json
not the deleted message from that channel
Before you initialise it
Remove the del part and try
async def on_message(message):
if "I am"=="i am".lower in message.content and message.author.bot == False:
await message.channel.send("I am UwU-BOT")```
oh no, {} were, but after the command they disappeared
this code should not be case sensitive pls help how do i do that
Nothing happens
Because you want to add something to the json , for that you need to read the earlier data and add the new data to it
No error either
pls help meeeeeeee
use .lower() on both sides
ok
!e py if "I AM".lower() == "I am".lower(): print("k")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
k
what should I do?
json.load and read the data first , add data to it as you do in a dictionary
just to save one function call you may set the second string lowercased by default
Yea
ytdl?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
in json file add {}?
sed not ytdl 😓
At the initialisation, yes
??
is there any way or a general way
🙏
wrong mention mb
it stopped working for I am
kk
You implemented it wrong , mb
🥲
Yea lemme see
Yeah , now try adding the values and stuft
stuff?
the keywords in the json and their values
As you had earlier
@bot.event
async def on_message(message):
if "I am" in message.content and message.author.bot == False:
await message.channel.send("I am UwU-BOT")
pls fix this pls
you didn't add lower anywhere
i reverted it
It's correct then
what?
i want it to be case insesnsitive
means I AM should also be like i am
Add lower function then?
then I am aint working
make it message.content.lower()
May I ask how familiar are you with python?
2 weeks
he probably got in discord.py instantly instead of learning python first
Hm you should learn atleast basic python functions and usage before making a dc bot
okay so lemme learn that first then come here
bye
That's a good idea
Yea cool
ight so sarthak
back to my weird problem 
nah I prefer disnake instead
oh
Indent
is it better?
gimme a moment , I'll switch to my pc
ight
Kindof , it's developed by the developer of dislash.py which was used for slash commands with dpy
And is well maintained
niceee
The indentation is correct.
ig I'll give it a shot
after dpy was archived
I've been looking for good alteratives
not really a big fan of djs
since I'm not comfortable with node.js
i c
ok so after removing the del part , you face the same issue?
yeah
but before it was only sending the del part, not the sniped message
like when the code was all together, which was odd
hm , use string ids instead of int , do str(message.channel.id) in the delete message events
and , use str(channel.id) while getting the data too
You can print the dictionaries to make sure that the data gets added
if you don't want to work with a discord.py fork , hikari exists
!PyPi hikari
Slash implementation in Disnake in case you're interested https://github.com/sarthak-py/disnake-template/blob/main/bot_examples/basic_bot.py#L73-L81
tysm 
bot_examples/basic_bot.py lines 73 to 81
@bot.slash_command(name = 'name' , description='Command Description')
async def slash_cmd(inter: ApplicationCommandInteraction ):
'''
Slash command implementation ;
Options can be added to the slash command as in normal commands
https://disnake.readthedocs.io/en/latest/ext/commands/slash_commands.html#option-types
the ApplicationCommandInteraction object is similar to commands.Context
'''
await inter.response.send_message('The message to send')```
yeah still nothing
Tried printing it?
Yw 💙
it's not letting me code it so i can print it
or im just stupid rn
Wdym letting it code it 🤨?
yeah told u im just stupid rn LMAO
lol , I'll try to test the code as soon as my device allows me connect itself with internet
oof
fully functional for me
do you delete any message lol
yeah i do
that's the wrong code ur using
Why my bot always goes offline randomly, this is the code and i use uptime robot:
py
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "FTS está listo."
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
does your bot have message intent?
snipe_message_author = {}
snipe_message_content = {}
@commands.Cog.listener()
async def on_message_delete(self, message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await asyncio.sleep(60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
@commands.command(aliases=['s'])
async def snipe(self, ctx):
channel = ctx.channel
try:
e = discord.Embed(
timestamp=datetime.utcnow(),
title=f"{snipe_message_author[channel.id]}",
description=snipe_message_content[channel.id],
color=0x9641EA
)
e.set_thumbnail(url=snipe_message_author[channel.id])
await ctx.send(embed=e)
except:
e = discord.Embed(
color=0x9641EA,
description="No messages have been deleted"
)
await ctx.send(embed=e)
this is the code u need to have
yeah it does
is snipe_message_author a top level variable?
That's the one i'm using, that code was the base of my current code
ow waitup
wdym a top level?
Can someone help me
not inside a function , acessiable to all parts of the code
this is what it looks like, so i guess?
Can someone help me
message not getting saved is not the problem , you try to set the user as the thumbnail of the embed lol
oh
@slate swan Can you help me..
but so how can i fix that?
your problem?
Why my bot always goes offline randomly, this is the code and i use uptime robot:
py
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "FTS está listo."
def run():
app.run(host='0.0.0.0', port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
cus i need the author pfp as like the small icon
you want the member's pfp there right
wait im stupid, thats not even the right spot LMFAO
its not supposed to be thumbnail i think
oh just use (url=(the_dictionary_name[channel.id]).avatar_url)
@slate swan
it comes back online again?
how did you add it in uptimerobot
lemme show
btw dont use replit
especially as a host
why and what should i use
host it on your IDE locally
Use a hosting service. Not all of them are paid, there are many free options.
well i dont really know how
click run
any recommendation
a free one
do you call the keep_alive function/
yea
somehost
https://somehost.xyz is a great one imo.
Free and paid hosting
heroku?
heroku is not a host either , no different from replit
its easy enough
Their support team is also very good. totally not vouching for myself.
When I have the del message there too it doesn't send the "sniped"
why _content , you needed the author no
because if i remove content i get an error
( also remove del )
I need deleted message
to check if there is a deleted message or not
bruh you save member in the _author dictionary
Or should I make a separate error message?
actually nvm, that wont work for this
🤦♂️ just replace _content with _author there
oh right, i just did content on accident and was like huh?
thx works now
cool
You can make a dictionary inside a dictionary.
snipe_message_content[channel.id] = {"content": "some content", "author": author's id}
Then you'd have both content and author in the same dictionary without needing 2 dictionaries.
I was recommended that by a friend but never got a chance to use it
@client.command()
@commands.cooldown(1,120,commands.BucketType.user)
async def rob(ctx,member:discord.Member=None):
await update_bank(ctx.author)
if member == None:
await ctx.send(f"Who do you want to rob {ctx.author.mention}?")
else:
with open("bank.json","r") as f:
bank = json.load(f)
await update_bank(member)
success = random.randint(1,2)
if success == 1:
earned = random.randint(50,1000)
memberwallet = bank[str(member.id)]["money"]
if earned >= memberwallet:
earned = memberwallet
bank[str(member.id)]["money"] -= earned
bank[str(ctx.author.id)]["money"] += earned
with open("bank.json","w") as f:
json.dump(bank,f,indent=2)
await ctx.send(f"{ctx.author.mention} you stole {earned}$ from {member.mention}")
if success == 2:
lost = random.randint(50,1000)
authorwallet = bank[str(ctx.author.id)]["money"]
if lost >= authorwallet:
lost = authorwallet
bank[str(member.id)]["money"] += lost
bank[str(ctx.author.id)]["money"] -= lost
with open("bank.json","w") as f:
json.dump(bank,f,indent=2)
await ctx.send(f"{member.mention} someone tried to steal money from you! {ctx.author.mention} paid back {lost}$")
It doesent respond
error , expected result , got result...
me?
yea
Ouch
it always crashed
it doesent respond
^^ not at all like my last code
Hahaha
As usual, just print success :D
Wait, I think there's a possibility it can also be 3
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
Nvm, was another function
it can be 1 2 or 3?
Nahhh
I dont want random choice
does the command get executed? any error handler or something
async def update_bank(user):
with open("bank.json","r") as f:
bank = json.load(f)
if not str(user.id) in bank:
bank[str(user.id)] = {}
bank[str(user.id)]["money"] = 0
bank[str(user.id)]["bank"] = 0
with open("bank.json","w") as f:
json.dump(bank,f,indent=2)```
so , does the json get updated?
no
only if its not inside
so for example
if 770210759359070209 is not in the json
it puts 770210759359070209 in the json
PS C:\Users\Awesome\Downloads\hhdhhdh> npm install sqlite3
npm WARN deprecated node-pre-gyp@0.11.0: Please upgrade to @mapbox/node-pre-gyp: the non-scoped node-pre-gyp package is deprecated and only the @mapbox scoped package will recieve updates in the future
npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.
npm ERR! code 1
npm ERR! path C:\Users\Awesome\Downloads\hhdhhdh\node_modules\sqlite3
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node-pre-gyp install --fallback-to-build
npm ERR! C:\Users\Awesome\Downloads\hhdhhdh\node_modules\npmlog\log.js:227
npm ERR!
npm ERR!
npm ERR!
npm ERR! SyntaxError: Unexpected end of input
npm ERR! at Object.compileFunction (node:vm:352:18)
npm ERR! at wrapSafe (node:internal/modules/cjs/loader:1026:15)
npm ERR! at Module._compile (node:internal/modules/cjs/loader:1061:27)
npm ERR! at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
npm ERR! at Module.load (node:internal/modules/cjs/loader:975:32)
npm ERR! at Function.Module._load (node:internal/modules/cjs/loader:822:12)
npm ERR! at Module.require (node:internal/modules/cjs/loader:999:19)
npm ERR! at require (node:internal/modules/cjs/helpers:102:18)
npm ERR! at Object.<anonymous> (C:\Users\Awesome\Downloads\hhdhhdh\node_modules\node-pre-gyp\lib\node-pre-gyp.js:16:11)
npm ERR! at Module._compile (node:internal/modules/cjs/loader:1097:14)
npm ERR!
npm ERR! Node.js v17.1.0
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Awesome\AppData\Local\npm-cache\_logs\2021-11-20T09_14_14_016Z-debug.log
this is not related to python
so does any of the if statement get executed? add print statement in them to check if any of the work
then what
node.js
send me server
huh
now it works
you should look for it yourself not have others send it to you
they said not related to djs
thats just a way to check if a condition works py if <condition1>: print('condition 1 works') elif <condition2>: print('condition2 works')
now everything works
¯_(ツ)_/¯
how can someone be so dumb
We don’t need to be condescending or bully others. To some people this may be the only server they know of, it’s not necessarily small. If someone’s in the wrong place just redirect them.
This is related to NPM which is a node package manager for JS, you may receive more specific help in the programmers hangout. discord.gg/programming
is somehost.xyz legit
is there anyway to count the number of bots in a guild?
How i fix this: container@pterodactyl~ Server marked as offline... [Pterodactyl Daemon]: ---------- Detected server process in a crashed state! ---------- [Pterodactyl Daemon]: Exit code: 1 [Pterodactyl Daemon]: Out of memory: false [Pterodactyl Daemon]: Aborting automatic restart, last crash occurred less than 60 seconds ago.
how to check which users/bots have been mentioned in a message ?
I'm creating a ticket system, it just doesn't create the channel
code:
asynchronous def ticket (ctx):
guilda = ctx.gilda
embed = discord.Embed (
title = 'Ticket system',
description = 'React :envelope_with_arrow: to create a ticket.',
color = 0
)
embed.set_footer (text = "ticket system")
msg = wait for ctx.send (embed = embed)
wait for msg.add_reaction (":envelope_with_arrow:")
reaction = wait for msg.fetch_message (msg.id)
wait for client.wait_for ("reaction_add")
wait for client.wait_for ("reaction_add")
if reaction == ':envelope_with_arrow:':
await guild.create_text_channel (name = f'ticket - {reaction.author.name} ')```
`
Error:
Ignoring exception in command ticket:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await chorus (* args, ** kwargs)
File "main.py", line 33, in ticket
reaction = await msg.fetch_message (msg.id)
AttributeError: 'Message' object has no attribute 'fetch_message'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke (ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected (* ctx.args, ** ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError (exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'fetch_message'
this doesn't seem to be related to discord bots
there are so many typos in this code
how make blacklist system?
wdyn
you make a check and a db
^
if you still need help in 10 min ill make an example
can i have help please : (
справедливо
about this
yes please
this isn't how you use wait_for()
check the docs
docs
?
I don't have a good command of English so I don't understand much about the docs
okay
ohhh
i guess it is the translator issue 
what is the problem
@client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that 👍 reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '👍'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('👎')
else:
await channel.send('👍')
This is how you use it
oh
@client.event
async def on_message(message):
if message.content.startswith('$greet'):
channel = message.channel
await channel.send('Say hello!')
def check(m):
return m.content == 'hello' and m.channel == channel
msg = await client.wait_for('message', check=check)
await channel.send('Hello {.author}!'.format(msg))
Waiting for the user repy
!d discord.ext.commands.Command please use this brooo
class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
🥲 i just gave the example from the docs for understanding
Oh hmm
thanks
👍
Hey, just wanted to ask is there a discord.py API, about questions and etc. ? For a trivia command.
Hey
I am starting to code on VSC
how do i install discord.py
i have python and vsc
pip install discord.py
I recommend you to first learn Python, after that to start trying to make some commands in discord.py.
cmd prompt
how would i fetch the desc of my command to display in my help cmd
if command.short_doc:
embed.description = command.short_doc```
doesnt work
!d discord.ext.commands.Command.description
The message prefixed into the default help command.
ty
short_doc is the text in py ''' '''
inside the function
ah
yeah " is recommended for docs
i am creating a ticket system function. It works but only one user can do it, for example:! Ticket <user> has created the ticket channel, if another user clicks on the reaction for the ticket, nothing is created
code:
asynchronous def commission (ctx):
guild = ctx.guild
embed = discord.Embed (
title = 'Commissions',
description = 'Do you need a commission? Click the reaction below to contact a Dev. '
)
msg = wait for ctx.send (embed = embed)
wait for msg.add_reaction (":envelope_with_arrow:")
msg = wait for msg.channel.fetch_message (msg.id)
while true:
def check (reaction, user):
return str (reaction) == ':envelope_with_arrow:' and ctx.author == user
wait client.wait_for ("reaction_add", check = check)
ticket_channel = wait guild.create_text_channel (name = f'Commission for ・ {ctx.author.name} ')
wait ticket_channel.set_permissions (ctx.author, send_messages = True, read_messages = True, add_reactions = True, embed_links = True, attach_files = True, read_message_history = True, external_emojis = True)```
!e ```py
def name():
'''
doc str
'''
pass
print(name.doc)```
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | doc str
003 |
You really love spaces.
Discord doesn't add spaces
sure
@cog_ext.cog_slash(
name="ping",
description="Check if the bot is alive.",
)
@checks.not_blacklisted()
async def ping(self, context: SlashContext):
"""
Check if the bot is alive.
"""
embed = discord.Embed(
title="🏓 Pong!",
description=f"The bot latency is {round(self.bot.latency * 1000)}ms.",
color=0x42F56C
)
await context.send(embed=embed)
There's no space added
¯\_(ツ)_/¯
It sends exactly what you copied from your code, and therefore the spaces in your code
why do you use while true?
for the cicle
how do i ban somebody and check if the user has perms?
do you break it anywhere
wdym
while true is in infinite loop as long as you dont break it
ik
then where do you break it
error is this
ye cuz it checks for the command author lol
you have everything under your eyes
uhm
ctx.author is the command author
can i type you in dm? please
U can but i wont help
you need ctx parameter
You forgot the ctx argument in the parameters list
ctx, user:...
ctx is always required
So many dpy forks lol
okay
sps
I'm not a fan of forks
I'd rather use a completely different library made from scratch than use a discord.py fork
Id rather use a fork then relearn everything again
Using a new library is just about reading the documentation, it's not rocket science...
you dont need to 'learn' it
Yh cba for that
if you know python and OOP everything's cool
tried hikari yet?
I learnt as i went along
I never properly learnt python
:/
But python easy to work out how to do stuff
those line numbers look scary
xD
idk what to say
Blacklist_list isnt part of ctx u have to get the guild from ctx.guild and then link it to blacklist from the json somehow
Someone hasn't discovered ✨ cogs ✨ yet
I just want certain people not to be able to use the bot
Per guild or overall?
If overall just match their id to a list from a json
Have you defined blacklist_list somewhere?
overall
Per guild u need a dictonary
Ok, just store their ids in a json list, and then match their id against that list
HOW?
xD
But it wont be ctx.blacklist_list itll just be blacklist_list
not json?
And at the beginning of ur code ur gonna wanna open blacklist.json as blacklist_list
can we go to private messages?
Why?
comfortable
Hey
code :
@commands.command(pass_context=True)
async def getguild(self, ctx, id : int):
guild = bot.get_guild(id)
channel = guild.channels[0]
invitelink = await channel.create_invite(max_uses=1)
await ctx.author.send(invitelink)
await ctx.send("✓")
error :
Ignoring exception in command getguild:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/My-First-Program/cogs/Owner Commands.py", line 212, in getguild
channel = guild.channels[0]
AttributeError: 'NoneType' object has no attribute 'channels'
do someone know why?
Make a type hint to a discord.Guild object instead of an int
Then you already have the guild object and can remove the get_guild part
the id your provided as guild id was not a valid one
or the bot is not in the guild
^
I already foxed it. It was something else but ty anyways :D
I had to use
self.bot.get_guild
instead of bot.get_guild
Should still change the type hint
Guys, how do I check if my bot is already in a voice channel?
!d discord.ext.commands.Context.voice_client
property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
ping?
guys I'm so suck with this library
cant relate
lmao
how do I make a server lockdown command? I know a method for closing a guild channel but idk for the entire server channels
iterate thru all the channels of the guild
this doesnt go any further
if ctx.voice_client.channel is not None:
return await ctx.reply("I am already in a voice channel")
!d discord.Guild.channels
property channels: List[GuildChannel]```
A list of channels that belongs to this guild.
ok thanks
ctx.me.voice.channel
oh okay thanx
yea , so?
that would be an error everytime the bot is not in a voice channel 😑
it stops right there and doesnt work out the rest of the function
because you use return
It would return none if it is not in a voice channel lol
@commands.command()
async def join(self, ctx):
if ctx.message.author.voice is None:
return await ctx.reply("You need to be in a voice channel to use this command!")
if ctx.voice_client is not None:
return await ctx.reply("I am already in a voice channel")
await ctx.author.voice.channel.connect()
embed = discord.Embed(title="VC Status", description="Joined your voice channel!", color=ctx.message.author.color)
await ctx.send(embed=embed)
no
.voice itself would be none , so using .channel would raise an error
does the bot not join a channel even if you are in a voice channel and the bot aint?
yep
if ctx.voice_client is not None:
return await ctx.reply("I am already in a voice channel")```
is causing the error
it means that the bot is in a vc
Maybe you should think about checking the voice state too, or do you need ppl to do everything for you?
I gave him a check for the channel not for the voice state
thats not what he asked
ye mby?
VoiceState can be none , you know? and they need to check if the bot is in a channel or not , so how do you except the None value to return a channel
thats what voice_client meant for
You seem to not read what i say and think you are a kind of master of it, which is kinda funny after the look at your git.
Anyway @upbeat otter check for the voice state and channel
Atleast not misleading someone
nvm, i'll figure it out myself ,-,
if ctx.me.voice and ctx.me.voice.channel:
thats it
if ctx.me.voice.channel :
``` at this point , if the bot is not in a vc , the `.voice` would be none , but since you have .channel after it , it still gets executed raising an error , that's what I meant
Leave it python elite
Guys is there anyone that is good in making discord bots and minecraft ?
i have a question
Basic python, it would raise a TypeError since NoneType doesn't have the attribute channel lmao, he just told you nicely and you get mad at it, cringe
Instead of coming acting like a sherlock holmes, u shoudl read the entire discussion, as i said he asked for a channel thus i gave him. Thats why u he has to check the voice state and then channel
You could've gave him something that wouldn't lead him into an error every time the bot isn't in a voice channel
if ctx.me.voice and ctx.me.voice.channel:
...
As if youve read the discussion, he said it kept erroring while he was doing what he told him to not was i was telling him to
But nice try
@slate swan oh?
I'm blind mb
Has anyone documented approximate values for the rate limits of different endpoints anywhere?
Isn't that supposed to be in the discord docs?
@bot.listen()
async def on_message(message):
await bot.handler.propagate(message)
await bot.process_commands(message)
print(message.content)
for i in Filter:
if i in message.content:
await message.channel.send("Please don't use bad words")
# await message. delete()
for f in abcd:
await message.channel.send('COOL')
``` I created this code to check if a invite send by someone has upper case letters or not
but it doesn't works
I am bad in bot dev 😕
The API documentation only documents how to receive rate limit information dynamically, but doesn't include information on their approximate values, as far as I can tell.
First things first, what's bot.handler.propagate
Second, since you're using .listen you don't need process_commands, so just remove it
Third, that doesn't exactly look like it would check if an invite is inside a message
Oh
I have created a list containg discord.gg, discord.app
Kinda sucks that they're not in the docs tbh
Oh alr
What's Filter and what's abcd
Filter is to check if there is any bad word
So Filter is a list of bad words
oh wait I should put the 2nd code inside of invite loop
Yes
Alr
Can someone tell me what advantages pycord has above disnake
None lmao
If anything it's worse
Anyone who says that pycord is the best fork is just a simp of the youtuber guy or simply biased
Or a mod from the pycord community itself 😂😂
I've also been told disnake has a donation thing, even though most of the library was written by someone else...
But pycord has more members
!source
just gotta yoink the eval feature
That's the only thing pycord did better than disnake, advertisement
Besides that, nothing, and more popularity != better
They are dynamic, so there ain't an approx value. They vary a bit too much for each bot
anyone know a search api?
I'm currently using pycord, if I want to switch to disnake, and just do pip uninstall pycord pip install disnake, would it work
Wait wrong link
Mhm
Okay thanks!
So what's better in disnakee than pycord??
hope it doesn't create any errors
Oops
Because I have to choose one
U gotta change your imports
That's because someone wanted to donate, it didn't originally exist and wasn't a planned thing either
Whats the link to that directory that you can send instead of a .txt file?
Pretty much everything you can think of, even has more feature like commands.Param and soon enough even injections
Ok
Tf? @unkempt canyon deletes that website?
yes
Then I will learn disnake
Which website
its frequently used in a negative tone
I thought a moderator deleted that message before ;-;
Sorry
Ah, understandable. Thanks for the clarification and sorry for doing that :(
any search api?
There is google search API
When I used this command it gave this error:
Command raised an exception: AttributeError: 'Context' object has no attribute 'delete_messages'
@bot.command()
async def delete(ctx, message_id):
msg = await channel.fetch_message(message_id)
await msg.delete()```
channel isn't defined
i used ctx too
i did O-O
what is pycord
Also idk about other forks but some members and contributors of disnake monkey-patched the extensions for dpy (like discord-ext-menus, jishaku, etc)
Another fork of dpy
oh got it to work now
Kratos didnt thor kill u already
When you typo my username 😔
wut @slate swan Thoris gonna kill u run away
Who's Thoris
Baldurs Brother dum dum
Ring bells
Nope
U killed Baldur
if u remember
Wait U arent Kratos
U are kraots
ma bad
That's what I'm saying
😟
How do i make so the channel name gets changed to message.author.name i tried this but didnt work: await message.channel.edit(name="{message.author.name}-ticket")
do await message.channel.edit(name=f"{ctx.author.name}-ticket")
ok
tysm it worked
oki np
i have an error for connecting my mongodatabase
File "main.py", line 49, in on_ready
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/database.py", line 886, in list_collection_names
for result in self.list_collections(session=session, **kwargs)]
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/database.py", line 848, in list_collections
return self.__client._retryable_read(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1514, in _retryable_read
server = self._select_server(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1346, in _select_server
server = topology.select_server(server_selector)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 244, in select_server
return random.choice(self.select_servers(selector,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 202, in select_servers
server_descriptions = self._select_servers_loop(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/pymongo/topology.py", line 218, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 61990553e4f23a8b964d1d0f, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('dbfury-shard-00-00.u4oj3.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('dbfury-shard-00-01.u4oj3.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('dbfury-shard-00-02.u4oj3.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]>```
Ye except that
Hi I have this code
from datetime import datetime as dt
client.launch_time = dt.utcnow()
@client.command()
async def uptime(self, ctx):
delta_uptime = dt.utcnow() - self.bot.launch_time
hours, remainder = divmod(int(delta_uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
print(f"Der Bot ist seid **{days}Tagen**, **{hours}Stunden** und **{minutes}Minuten** online")
await ctx.send(f"Der Bot ist seid **{days}Tagen**, **{hours}Stunden** und **{minutes}Minuten** online")
Its just a uptime command but when I want to run it I get the following error
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing
what is the problem?
youre not in a class
remove the self
in self.bot.launch_time too?
yes.
ok
copy and paste is never recommended.
ok thx for your help
hi I want to make a command for my bot that compares the stats of 2 players from the hyperlands api. here's my current code, i don't understand how I can make the bot differentiate between the first user and the second (because usernames can have spaces in them)
https://paste.pythondiscord.com/yecokodigi.py
why does this return none?
result = await _bot.fetch_guild(911627141798572042)
await _ctx.send(result.owner.name)

