#discord-bots
1 messages · Page 553 of 1
await trigger_typing()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Triggers a *typing* indicator to the destination.
*Typing* indicator will go away after 10 seconds, or after a message is sent.
i need help can anyone tell me the commnd for streaming
!avater
!avatar @unkempt canyon
A bot application can't steam to a voice channel. @slate swan
Hihi
It's too late but...
@bot.command()
async def Test(ctx):
async with ctx.typing():
await asyncio.sleep(1)
await ctx.send("Done!")
Someone says it doesn't work, But it works!!!
Okay Okay... am I too late?
😐
can someone pls send a discord bot code for currency system
No
WDYM
Code for VC?
you just replied to yourself?
Hi, my first section works but my second section doesn't work, why is that?
@client.event
async def on_message(message):
if message.author.id == ********:
await message.add_reaction(":Discordjs:")
else:
return
@client.event
async def if_messsage(message):
if message.author.id == ***********:
await message.add_reaction(":white_check_mark:")
else:
return
your only allowed to have 1 on_message event iirc
so how do I make the second section work?
also if_message isn't an event
oh
just use the first one
and check for multiple things
ok
like if ... or ...:
👍
i did elif
hhey i made dropdown menu but when i select any menu so it not chnage pls tell me whats wrong in my code
check the status of the website
wdym "it not change"
can you elaborate? errors, what you expected it to do, what it's doing?
hey, i wanna secure my tokens with .env, but i cant use dotenv so i used dotenvy. and because that i got error
I can't get it to instant delete
replit?
instant delete?
like i want the message sent by bot to delete instantly
So the one in the for loop?
it sents @fallen gyro Catch +i i want this to be deleted instantly
await m.delete not working
Well your not delting that message lol. You should set that equal to a variable then you can delete it
(Send returns the Message object to delete)
didn't get it
just use delete_after kwargs of your send, set it to 0 if you want to delete it with no delays
s = response.content.split(" is ")[1].replace(".","")
#response.delete()
print(s)
x = get_mon(s)
#print(options)
print(x)
first_options = x
for i in first_options:
await message.channel.send("@ catch "+i)
await m.delete()
can you edit it to be correct?
not a coder..
!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**.
Read le docs
Because your using an invalid token
Got an on_message?
Delete_after
Care to show how you define bot
Sure, the bit you sent.
And how are you trying to call your command
pycharm
@ is your prefix?
uh
Is there a reason you can't use https://pypi.org/project/python-dotenv/?
that was for mentioning someone
wait i think i cant install it
And what makes you say that
um i used dotenvy
i got error when downloading dotenv on my pycharm
ok tq, i got the solution
hi
how can i get info from a user, regarding that user in the server or not (by ping).
what does that wikipedia api wrapper return as a result?
also, you prolly wanna do name="look" then add aliases 👍
there's a difference between a member and a user object
check em both out
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
smells sussy
i am making a verification level
that only account with email
lmao ok i was jk
you can't
that's private user information bud 👍
from discord document
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
hmm, smells like a selfbot only feature to me, otherwise i don't see how it would work
How can i change bot status?
Ty
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
how can I count the voice time that the users have done?
Well, how can i set the bot status as "Watching"?
!d status
!d discord.Status
!d discord.Streaming
class discord.Streaming(*, name, url, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that represents a Discord streaming status.
This is typically displayed via **Streaming** on the official Discord client.
x == y Checks if two streams are equal.
x != y Checks if two streams are not equal.
hash(x) Returns the stream’s hash.
str(x) Returns the stream’s name.
Smh
@bot.listen()
async def on_message(message):
if message.author.id == 579353526371614743:
return
if message.content == 'hi':
await message.channel.send("hello")
here how do i set like i want my bot to respond hello to hi but not just hi i mean like if the message sent is "hi i am kira"
bot still respond hello if it's "hi how are you" i want the bot to still respond hello i want it to respond hello if the message sent by the person contains "hi"
how do i do that
i want bot to respond hello everytime the message contains "hi"
the message sent by bot user
Me: hi how r u
bot:hello
me:Hi ok
bot:hello
me: hi (anything random)
bot:hello
like this
didn't you already do that though
it's not working
again
loop through the message content
to check if the message
has a certain keyword
how
a for loop i guess
what's the command
what command?
to loop
you dont need a command to loop it
then
its basic python make a for loop that iterates through the message content
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
im not gonna help you if you dont know what a for loop is sorry
if message.author.id == 579353526371614743:
return
it won't respond to this id? if i put it like this?
ofc not
its a return statement
🤦 got it thanks smh some guy told me it'll only respond to this id if i put it there
how do you these kind of message?
colorful @slate swan
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@slate swan
ok
!ot please if its not related to discord bots
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
i made it
made what
ok
print("smh")
ok
Ngl i really really hate how discord made it so clicking channel mentions in embeds doesn't send you to that channel
mobile?
it wasn't a thing on mobile like ever
It was
only on pc
when
It used to be a thing on mobile last year
Ik bc last year I was using mobile a lot more often than I was using pc
Do we have to wait for slash commands to globally register?
Yes
How long
Depends
It can take up to 1h
Oh ok
you can use guild commands for testing. it's instant
^
I should've known that
read the docs on how to turn it into a guild commands
Alright
you cant convert a datetime object into a float
if you wanna convert to float
is it int?
i think better find other module
bruh
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
It is an integer
!e ```py
type pip install pyartificialintelligence
yes
#bot-commands please.
as datetime cant have
yes I can't convert to int
floats
u said you wanted to convert it to a float though
ill find something for you @viral pebble
bruh
thanks
i can also to int
!e
import datetime
print(datetime.datetime.utcnow().timestamp())
``` @viral pebble took me a long time lol
@lusty swallow :white_check_mark: Your eval job has completed with return code 0.
1634973474.812864
like this?
no
try this this would be better ```py
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time) ```
Bruh
im jest informing
well you can't convert a datetime object nor a string to float
exactly
@viral pebble
It's already a string if you use the string function
i think he was doing this <t:12345:t>
i meant his intention
there's not really much use of converting to float something other than dbms and timestamp
how do you convert 00:00:00 to a float though
#bot-commands please for code evaluation
i want to subtract datetime.now by other datetime it is possible?
just subtract it
yes it's possible
zerozerocloumnzerozerocolumnzerozer0
it will return a datetime.delta
yes
how?
how old are you?
datetime.now
14
@viral pebble
you don't act like it
ok
you want face reveal?
also stop trolling :|
sure
ok
no
but to subtract it I need to convert the datetime to int
!e
import datetime
print((datetime.datetime.utcnow()-datetime.datetime.now()).total_seconds())
```Here's a sample. Python bot uses utc as timezone so it will be 0
@lusty swallow :white_check_mark: Your eval job has completed with return code 0.
-4e-06
@viral pebble ignore the part that says -4e-06
Convert it then?
it's already an int
you just can't convert it to a float thats all
ok
!e
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | year: 2021
002 | month: 10
003 | day: 23
004 | time: 07:24:09
005 | date and time: 10/23/2021, 07:24:09
!d datetime.timedelta check what you can do with timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
#bot-commands bro
also #❓|how-to-get-help @viral pebble This is for discord bots stuff. Datetime is not covered
!eval print('how are you?')
you don't need the []
thanks
but do that in #bot-commands to prevent spam
wym?
no
what's your code so far?
we dont spoonfeed we help you
Hey @cyan rover!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
#bans player.
@client1.command()
async def ban(ctx, member : discord.Member, *, reason = None):
await member.ban(reason = reason)
#unbans player.
@client1.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return
this is the code
why copy code
i am using replit
ok?
so does that work|?
no
why
i don't know
is there a traceback?
no
then you didn t execute the command
but when i type ban @slate swan it not working
u sure
yes
show me how u did the command
yeah i will send a screen shot
- Does your bot have permissions
- Is the any error?
- Did you try doing
!ban @person#1234?
no i didn't try the 3 one
u said u tried banninng though
does ur bot have admin
yes it does
if it's permission related, it should raise a permission error
the cog is not loaded maybe?
@boreal ravine what's your bot for that?
my bot?
no error
Hey @cyan rover!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
yes it is
you have a link?
Its jishaku
!pypi jishaku
ohh nice
A discord.py extension including useful tools for bot development and debugging.
i'll try it in my server ty
Hey @cyan rover!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
@cyan rover Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
@cyan rover Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
can i dm
sure Ig
Doubt it is
btw curious whats that jsk thingy
jishaku
does it have intents
Why do you have both a Client and Bot...
You never run Bot is the issue
You only run Client
Smh, remove Client and just use an instance of Bot
oh ty
What
Read the code they linked
he only has commands.Bot not the client
client1 = commands.Bot(command_prefix = '.')
phrases = []
lol1 = ("unknown")
client = discord.Client()
...
client.run()
He does
wait there 2 thingies
uh huh
@cyan rover what @valid perch said only use 1 bot variable
so what do you mean
why do you even have 2 lol
should i remove client1
Get rid of client = discord.Client() and only use your client1
Can anyone tell me why this spams once the time is reached and not sleep
I am new, sorry if the code is stupid
Thank You
from discord.ext import commands
from datetime import datetime, time, timedelta
import asyncio
WHEN = time(7, 0, 0)
class Geyser2(commands.Cog):
def __init__(self, bot):
self.bot = bot
bot.loop.create_task(self.geyser_task())
async def call_geyser(self):
await self.bot.wait_until_ready()
embed = discord.Embed(
title=f"**Geyser will be up in 10 minutes**",
description=f"_This message will self destruct once Geyser ends_",
color=0xE2B1C8
)
embed.set_image(
url="https://c.tenor.com/iZfN5AJ6NZEAAAAC/sky-sky-children-of-the-light.gif"
)
channel = self.bot.get_channel(865581332737294336)
await channel.send(content=f"**TIME TO RUNNNN** <@&865992483351822356>", embed=embed, delete_after=1200.0)
async def geyser_task(self):
now = datetime.utcnow()
if now.time() > WHEN:
twohours = datetime.combine(now.date() + timedelta(hours=2), time(0))
seconds = (twohours - now).total_seconds()
await asyncio.sleep(seconds)
while True:
now = datetime.utcnow()
target_time = datetime.combine(now.date(), WHEN)
seconds_until_target = (target_time - now).total_seconds()
await asyncio.sleep(seconds_until_target)
await self.call_geyser()
twohours = datetime.combine(now.date() + timedelta(hours=2), time(0))
seconds = (twohours - now).total_seconds()
await asyncio.sleep(seconds)
def setup(bot):
bot.add_cog(Geyser2(bot))```
plss help i am not getting how to make dropdown for my help command
Bot is the one with commands support, but up to you 🤷♂️
ok
should be fine now
Well its a while True which never exits? If it's a different problem can you please provide some more details
Also, why have you made all your commands in on_message lol. That's what the command extensions for tejaji
no not working
bad way to unban someone
What did you do
i changed client1 with bot
Oh deary
Whats the error
Tbh, can you just send the updated code?
change your commands, events to bot too then
Did you replace every client1 with bot
yes
show your code
used ctrl f2 to replace all
i will try
not working
What isnt working
updated one
if you can pls can you edit the could and send it
no
ok
ok
You got linked something that explains it
Yea, I'm just gonna say copy this and spell shit right
Cos you didnt spell it right
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
listen, not lisent
read the docs
Read what we have given you lol
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
READ THE DOCS
@bot.listen not lisent
Lol what would we know
Why did you make your commands listen?
Because commands should be @bot.command and not @bot.listen 
As kayle said, if you saw it, edit the bot.event decorators
ok
i have to leave
Look at this
i will try and get back
Adios 👋
dpy will force your param to be an int, just cast it straight as int id: int
@bot.command()
async def test(message):
await message.send("Done!")
await asyncio.sleep(2)
await message.delete()```
`discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'delete'`
I want the bot to delete its message after 2 seconds
what are you trying to do here
you've mixed bot.event with bot.command
and? i can't?
in a bot.command() you pass the parameter ctx
not message, but you can get message by ctx.message
ctx is an instance of discord.Context which has information such as ctx.command, and ctx.prefix.
message -> discord.Message
ctx.message.delete
that is a possibility but maybe not exactly what he wants
yeah its work but my bot delete my message not him
m = await message.send(..) await m.delete()
you can do msg = await ctx.send('done') await msg.delete()
Does anyone here knows sql
a bit
Quite a few people most likely
Then can you help me
I'm sure many people can help you if you state your question.
Oh there was a I need help behind it, not just a general question. Intriguing
if you have an issue i'm sure people here or in #databases would love to assist.
But from many coding servers I get answers that the person who started helping say that he doesn't know sql after I send my code
So I asked
as I said, I don't know that much sql but I am willing to help. And after you send your code more than one person can help.
@client.command()
@commands.has_permissions(manage_guild=True)
async def levelsetup(ctx):
if client.user != ctx.author:
db = await aiosqlite.connect('expData.db')
cursor = await db.cursor()
await cursor.execute('''
CREATE TABLE IF NOT EXISTS guildData(
guild_id TEXT,
user_id TEXT,
exp TEXT
)
''')
await db.commit()
cursor = await db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)", (ctx.guild.id,
ctx.author.id, 1))
await ctx.send("Levelling system successfully setup for this server")
await db.commit()
if message.author.bot:
return
await client.db.execute("UPDATE guildData SET exp = exp + 1 WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
cur = await client.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
data = await cur.fetchone()
if data is None:
return
exp = data[0]
print(data)
lvl = math.sqrt((int(exp))) / client.multiplier
if lvl.is_integer():
await message.channel.send(f"{message.author.mention} well done! You're now level: {int(lvl)}.")
await client.db.commit()``` This is the code
Sending error wait
This is the error
data is a Nonetype, meaning you can't index it. Just remove the [0]
fetchone is returning None because it failed to fine a value
No from if message.author.bot: is on_message
Which is weird, because you check that
The code you sent us isn't the one your running
...
The one you sent us should work fine haha
if data is None:
return
That I edited in my repl after sending you
Well the one you sent here looks fine, use it and see
But if I use without [0] then no commands work and doesn't show any error also
that just means the check worked, and it is returning.
Basically the problem is the server which used levelsetup command my bot works perfect in that server but who didn't use levelsetup my bot not working in that and shows error
You can add a print or something to prove it
Prove what and to whom
To yourself why its not working
Can you look at the database and check the value your tryna find exists
And I have a doubt before I was not having levelsetup command. Everything was in on_message only and that time I had a line cursor.rowcount == 0: and that time it was working but when I split the code because of levelsetup command I had to remove that line as it showed error cursor is not defined
So maybe its because of that line
And just for on_message without levelsetup command the code was this ```py
@bot.event
async def on_message(message):
if not message.author.bot:
cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)", (message.guild.id, message.author.id, 1))
if cursor.rowcount == 0:
await bot.db.execute("UPDATE guildData SET exp = exp + 1 WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))
cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id))```
And going on
So that time it was working and now again I added cursor.rowcount line then this error goes. Then it shows cursor not defined
These all things made me think its because of that line
I am correct ot not
I don't know
just as a recomendation; I don't particularly know what is going on here, but you can do py if message.author.bot: return and this means that you don't need to pile on lots of indents.
@bot.command()
async def test(ctx):
msg = await ctx.send('done')
await ctx.send(f"{msg}")
await msg.delete()```
`IndentationError: unindent does not match any outer indentation level`
Where i have `IndentationError`?????
what editor are you using?
I have that
Sublime text
you did if not message.author.bot
That was before when there was no command levelsetup. Scroll up and see my current command
I am trying to add multiple reactions to a message. Currently I am adding the reactions one at a time through a loop. I wanted to ask if there is a way to add multiple reactions at once?
await search_query_sent.add_reaction(numbers[i])```
i dont think so
nope.
Got it. Thank you
maybe you do @client.evento('on_message') async def estaListo
otherwise, I'm not sure.
What does this mean?
Hello, can you help me to place an order in a discord bot that allows to put roles thanks to reactions under my message?
How can we broadcast messages through each commands?
Like when u click a reaction, another message gets edited or deleted
^ Another example, I send &test and it says "Hello"
I then send &test2 and the message "Hello" from the first command: &test, gets edited to "Hello!"
Ok I somehow made the commands to work but the level is not increasing
¯_(ツ)_/¯
how much shards do you think it needs for a discord.py bot with 60 servers?
0
0
you don't needs shards that early
you shard when you have over 1k servers
^
hmmm
i sharded my bot with 3,1k shards 🤣
nice
¯_(ツ)_/¯
You can modify the base library code
Like dpy internals
Go find where it calls on ready and change that
How accurate should I consider the member cache?
such as client.get_user() vs await client.fetch_user()
They are the same
Just second makes an API Call
I don't think there's any difference (at least I never had a problem with it)
Yups
Whenever a member is edited
Ah, ok thanks
using get_x is usually better
Ik...
i have a command that makes my bot be quiet for 10 seconds using synchronous time.sleep() but after the sleep ends, the bot responds to all commands sent during the sleep period (i know why this is happening, just looking for a fix) and this is not what i want. does dicsord.py have a list of send message taskts that i can loop through and task.cancel()?
please ping me if you respond
Why do u even wanna block the bot for 10 seconds...?
you make a check and see if its offline.
for example:
@bot.command()
async def sleepBot(ctx):
bot.sleep = True
@bot.command()
async def awakeBot(ctx):
bot.sleep = False
@bot.check
async def respond(ctx):
if bot.sleep and ctx.command.name != 'awakeBot': return False
return True```
and with this, you can use an asynchronous wait to unsleep it. For example:
@bot.command()
async def sleepBotTimed(ctx, time:float):
bot.sleep = True
await asyncio.sleep(time)
bot.sleep = False```
you can put this on on_message instead so you don;t have to edit all commands
@maiden fable it can be useful if you have another instance of the bot running.
what?
you can avoid typing this if bot.sleep and ctx.command.name != 'awakeBot': return False line by putting it in on_message instead
no.
do you know what a check is?
ohh wait it's a check lol
i didn't see the decorator
i read that as bot.command()
How to make it so that the bot says like- Watching <number of members> members
and how do I substract the number of bots from it
you can get the number with guild.member_count.
you create a task. For example:
@tasks.loop(seconds=540)
async def changePresence():
await bot.change_presence(name=f"Watching {len(bot.users)} members.") # I can't remember what precense change is.
changePresence.start()```
o thx
wait, bot.users is a valid attribute?
maybe its a new thing that discord decided to add lol
!d discord.ext.commands.Bot.users
ohh it is. just found that out
property users: List[discord.user.User]```
Returns a list of all the users the bot can see.
no. always has been here.
oh lol
Wait I thought this wasn't So where'd I'd get my intentions questioned instead of an answer
async def add(ctx):
SPREADSHEET_ID = 'spreedsheetid'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"```
At the moment you can if you type "!add ," it submits with no fields. Is there a way with this code to make it so you have to have some info to the fields before it accepts so if i type "!add hey," it shouldnt accept same goes with "!add ," it should accept if it is: "!add hey, hey"
I gave you the answer.
I don't want to change the status, just make it not respond to anything
Wait does the bot not respond if its status is sleep/offline?
my method doesn't change the status.
@last tapir
Anyone? ❤️
I replied to the wrong person, sorry
Yeah that looks like it'd work, thanks I'll try it
Nobody who can help a helpless soul who have spend hours trying to figure it out?
Be patient man you asked 4 minutes ago
Sorry.
Also you should edit the post and add "```py" code here and "```" at the end to get syntax highlighting
It makes the code easier to read
Wait I did do the Hey ?
correct.
Damn! :/
ca u format it
```py
like this
```
Let me do it.
didn't u ask for help yesterday
i asked you if if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None: was valid syntax
@client.command()
async def add(ctx):
SPREADSHEET_ID = 'spreedsheetid'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"```
It is valid. 😄
It doesn'
doesn't work the "py"
you sure
it does
@client.command()
async def add(ctx):
SPREADSHEET_ID = 'spreedsheetid'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"
like this.
you make a new line after the py
Arhh okay!
Wow actually readable now lol
It is valid in the sense. It will run if I choose the role, but its set to none so far.
@slate island error?
What you mean by error?
hi in discord.py i want to detect if a shard loaded itll log in the console that Shard loaded!
An error
Are you asking what the error is?
Like whats the problem with that code drace
mhm
how do i make a purge command
At the moment you can if you type "!add ," it submits with no fields (SHOULDNT SUBMIT WITH NO FIELDS). Is there a way with this code to make it so you have to have some info to the fields before it accepts so if i type "!add hey," it shouldnt accept same goes with "!add ," it should accept if it is: "!add hey, hey"
Basically the bot reads the "," if it has the decided amount of "," it accepts.
It shouldnt there has to be text you give the fields before it accepts.
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting bot’s messages...
and how do i get the amount of messages i purged?
to purge x amount of messages, you set limit=x.
thats up to you
So yeah.. any command or changes I can make to code so it has to have filled fields before accepting.
no i mean if i write !purge 100
and there are only 50 messages in channel how do i see how many messages the bot has deleted
yes add parameters like a function
Can you give me a example? Im lost been looking at the code for hours and researching.
like functions
I mean to the current code.
!e
def function(first, second, third, fourth):
pass
``` something like this
@boreal ravine :warning: Your eval job has completed with return code 0.
[No output]
yes
hmm im lost.
then learn more python
👍
you should be learning python functions before making a bot to understand what the commands do/are
I know what a python function is. I just don't know how I would insert it into my bot without breaking it.
Thats all. So im lost. 😛
huh
its literally the same thing
You should read up on discord.py documentation, it's pretty good
async def command(ctx, name, *, content)
is the same as
def command(name, *, content): #without ctx
i dont know what you dont understand
i know, but how does that solve the issue that you can post "!add ," without adding info to the fields "!add hey, hey".
Well you can catch the exception that is thrown when you try to call a function with wrong parameters and send a message saying the command needs parameters
you can add multiple parameters and do that e.g
async def function(ctx, name, *, content):
await ctx.send(f"You created a tag called {name}\nContent:{content}")
atm it adds fields to the Google Sheet API.
As you can see in the code. I don't think what you showed me solves that.. without completely changing the code.. i might be wrong though,
hm
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')```
I have made a purge command but I don't want it to delete a specific message.
Example:
Guitar: i am bored
Guitar: hello
Guitar: Hi (i dont want to delete this)
Guitar: !purge 1
``` This is what it should like after purging```
Guitar: i am bored
Guitar: Hi (i dont want to delete this)
lambda
?
A specific message by ID or content
ID
channel.purge(*, check=lambda m: m.id not in idlist)
thank you
- is not required
Sorry if I have a hard time explaining what I want. Sorry.
* acts as a placeholder, for example * can be limit=100...
But thanks for trying ❤️
but a function would fix the issue I am having with that people can just post a , and the bot accepts it?
hello what do you need help with @slate island
learn python. don't copy and paste code without knowing what it is. that is my solution.
no bro idk make music
i make my bot
but music no
you copy and pasted it all. don't act as if you wrote a tiny bit of any of it.
i copy and paste
@client.command()
async def add(ctx):
SPREADSHEET_ID = 'spreedsheetid'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))"```
Trying to make this code work. Basically you can cheat the bot to submit the info to the google sheet by just typing: !add ,
Basically it looks at how many commas there are by the chosen FIELD amount. So if you have 2 its 1 comma.
So basically you can post !add , and it submits or you can type !add hey,
I want it so it requires the fields to be filled before accepting and not the ,
I've been looking at it for a few hours, but find it hard to change without changing the code completely.
why idk make music
how do i temporarily suspend the asyncio event loop? "pasue" kind of
you need arguments, do you want users to separate them by spaces or commas?
for a specific command? you can tell your use case so there might be more alternatives
, is more than fine but if spaces are easier then of course I would prefer that.. I just need it to nto submit on the , only the fuilds needs to be added.
okay do this
on command, i want the bot to stop doing anything at all and start again after some time
async def add(ctx, *args):
for arg in args:
print(arg)
this will print each argument the user passes
you can use args to do whatever you want later on
Arhhh.. so change this:
async def add(ctx):
to
async def add(ctx, *args):
for arg in args:
print(args)
Yeah of course. Let me try 😄
So:
@client.command()
async def add(ctx, *args):
for arg in args:
print(arg)
SPREADSHEET_ID = 'idhere'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
your indentation is messed up
yeah select everything below the print and hit shift+tab twice, for vscode that works for me
Like this:
@client.command()
async def add(ctx, *args):
for arg in args:
print(arg)
SPREADSHEET_ID = 'idhere'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
I did do shift tab twice doe :p
@client.command()
async def add(ctx, *args):
for arg in args:
print(arg)
SPREADSHEET_ID = 'idhere'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
thats inside the for loop though, do this
@client.command()
async def add(ctx, *args):
for arg in args:
print(arg)
SPREADSHEET_ID = 'idhere'
RANGE_NAME = 'A1'
FIELDS = 2
# Restrict the command to a role
# Change REQUIREDROLE to a role id or None
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:
DATA = [ctx.message.author.name] + [str(ctx.message.author.id)] + [str(ctx.message.created_at)] + result
sheet.add(SPREADSHEET_ID, RANGE_NAME, DATA)
await ctx.message.channel.send('Your data has been successfully submitted!')
else:
await ctx.message.channel.send('Error: You need to add {0} fields, meaning it can only have {1} comma.'.format(FIELDS,FIELDS-1))```
indent size 4
and the for
Arhh okay! Let me try 😄
Still submits the data when i type "!add ,"
I dont fully understand how do you save an attachment 😅 i tried await attachmentname.save("some_name.mp4") but that didnt do anything, how can i use this as a file object (not discord.File but like local file)
you can get rid of these
REQUIREDROLE = None
if REQUIREDROLE is not None and discord.utils.get(ctx.message.author.roles, id=int(REQUIREDROLE)) is None:
await ctx.message.channel.send('You don\'t have the required role!')
return
by using
@commands.has_role(yourroleid)
Cheers. But i can still !add , :/
because it takes the comma as an arg, its no longer separated by commas
you can filter args by length
But thats an issue.
ˆ :)
you don't want anything shorter than 2 letters?
How do I filter by length if I may ask?
Nope. Not at all.
- as you can see the FIELDS is at "2" which means 2 fields should be filled a "," only count as 1? correct?
I don't get what you mean but
Atm in the code FIELDS is set at 2. Which means that it requires 2 fields to be filled to fit into 2 fields in the google sheet, but the "," count as an arg you said which means it fills 1 field? Then it broke what worked.
blacklist = [','] # put everything you dont want to add here
args = tuple(filter(lambda arg: arg not in blacklist, args))
it wont add commas separately
Hmm im confused now because my code basically it setup to split the fields by using the ","
you can add anything to blacklist,
blacklist = [',', 'pie'] won't add comma and "pie"
yeah you can get rid of those since you now get args separated by default
what is the correct way to implement prefix-less commands? check content of message in on_message() ?
What should I set result at?
result = [x.strip() for x in msg.split(',')]```
result is basically what you have as "args", its arguments separated by spaces and its a tuple
Im confused right now.. fuck
command = !add 1 2 3
result = args = (1,2,3)
why do slash commands take so long to register
Okay thats cool and all, but basically my script has a limit of how many fields you can post.. as you can see I chose 2 fields which means if by how the default code work.. if I had 2 commas.. then it would give me a error.
use guild_ids if you're testing, other than that it should take up to an hour to register globally
So by the looks of it, changing it to:
@client.command()
async def add(ctx, *args):
for arg in args:
print(arg)```
Kinda broke that.
do kwargs work in a command lol
I showed you how to get multiple args, you need to change your code accordingly to make it work
how can i use guild_ids for slash command while testing, other than just putting it in and taking it out manually
hm okay, thanks
In theory wouldn't i fix my issue by changing some of this code aswell instead of changing to arg?
msg = ctx.message.content[4:]
result = [x.strip() for x in msg.split(',')]
if len(result) == FIELDS:```
Put it in the commands.Bot variable if the lib ur using supports that
What are you tryin to do?
Can anyone give me an example of the on_raw_message_delete event?
Trying to get my bot to not bug. Basically i can submit to the google sheet by using "!add ," without adding anything to the fields. It accepts because it reads the amount of "," since fields is at 2. It looks for 1 comma. 3 2 and so on!
That means I can submit to it by doing !add , and it should be !add hey, hey.
and if I make the field 1.. i can just type !add and it submits.
I am completely lost.. just been trying the last 20 minutes..
how to keep multiple prefixes with prefixes.json thingy...
What bot object?
!pypi disnake
how can i set the welcome message when someone comes to the server
I've tried looking at the API reference, but I can't set channel permissions.
Please let me know if there is a site that explains it in detail.
i dont think a site like that exists but i'll give you an example,
await ctx.channel.set_permissions(role, send_messages=True, view_messages=True, connect=True, speak=True)
Guys, how do I get the bot not to mention the roles that I will tell him? I don't want him to mention the role "Players"
code: ```py
@bot.command(name="whois")
async def whois(ctx,user:discord.Member=None):
if user==None:
user=ctx.author
rlist = []
for role in user.roles:
if role.name != "@everyone":
rlist.append(role.mention)
date_format = "%a, %b %d, %Y %I:%M %p"
memberavatar = user.avatar_url
b = ", ".join(rlist)
embed = discord.Embed(color=0x2f3136,timestamp=ctx.message.created_at)
embed.set_thumbnail(url=user.avatar_url),
embed.set_author(name = f"{user.name}", icon_url = memberavatar)
embed.set_footer(text=f'Requested by - {ctx.author}',icon_url=ctx.author.avatar_url)
embed.add_field(name='Joined',value=ctx.author.joined_at.strftime(date_format),inline=True)
embed.add_field(name='Created',value=ctx.author.created_at.strftime(date_format),inline=True)
embed.add_field(name=f'Roles: [{len(rlist)}]',value=''.join([b]),inline=False)
await ctx.send(embed=embed)```
how i can do it?
!d discord.on_member_join this? @devout iris
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
its not Member join..
@bot.command(name="whois")
async def whois(ctx,user:discord.Member=None):
if user==None:
user=ctx.author
rlist = []
for role in user.roles:
if role.name != "@everyone":
rlist.append(role.mention)
date_format = "%a, %b %d, %Y %I:%M %p"
memberavatar = user.avatar_url
b = ", ".join(rlist)
embed = discord.Embed(color=0x2f3136,timestamp=ctx.message.created_at)
embed.set_thumbnail(url=user.avatar_url),
embed.set_author(name = f"{user.name}", icon_url = memberavatar)
embed.set_footer(text=f'Requested by - {ctx.author}',icon_url=ctx.author.avatar_url)
embed.add_field(name='Joined',value=ctx.author.joined_at.strftime(date_format),inline=True)
embed.add_field(name='Created',value=ctx.author.created_at.strftime(date_format),inline=True)
embed.add_field(name=f'Roles: [{len(rlist)}]',value=''.join([b]),inline=False)
await ctx.send(embed=embed)```
what
Yeah i guess
i was talking to the other person lol
is this event?
ah okey lol
yes @devout iris
just check if the user has that certain role
like
if player in user.roles:
#code
You don't understand I just want people not to see this role
not see roles?
thats impossible
so that the bot does not write this role*
oh
do this then
use list.remove() for this one e.g
if player in ...:
list.remove(player)
Thanks I'll try it right now
What's wrong with this code?
PermissionsOverwite()
whats wrong with this code?
async def reactionroles(self, ctx):
await ctx.invoke(self.bot.get_command("help"), entity="reactionroles")
@reactionroles.command(name="channel")
@commands.guild_only()
@commands.has_guild_permissions(manage_channels=True)
async def rr_channel(self, ctx, channel: discord.TextChannel = None):
if channel is None:
await ctx.send("You did not give me a channel, therefore I will use this one")
channel = channel or ctx.channel
try:
await channel.send("testing if i can send messages here", delete_after=0.05)
except discord.HTTPException:
await ctx.send("I can not send a message to that channel! Please give me perms and try again.", delete_after=30)
return
embed = discord.Embed(title='**Self Roles**')
desc = ""
reaction_roles = await self.bot.reaction_roles.get_all()
reaction_roles = list(filter(lambda r: r['guild_id'] == ctx.guild.id, reaction_roles))
for item in reaction_roles:
role = ctx.guild.get_role(item["role"])
desc += f"{item['_id']}: {role.mention}\n"
embed.description = desc
m = await channel.send(embed=embed)
for item in reaction_roles:
await m.add_reaction(item["_id"])
await self.bot.config.upsert(
{
"_id": ctx.guild.id,
"message_id": m.id,
"is_enabled": True,
}
)
await ctx.send("That should be all setup for you!", delete_after=30)```
it shows this error:
idk
read the error
probably some indentation error
your command was like this from what i can tell
async def func(ctx):
#code
await channel.send()
Hii, i was trying to make a music bot using youtube dl , so is there a way to get the information of how much current song played like (0:40/3:53)
Hello due to hosting a website for specific reasons on a dynamic ip i need a way to open it, i have decided to use discord. however i need help.
Need message to return as http://00.00.00.00:2030
I have the ip worked out just dont know how to add the http:// and :2030 to the start and end of the ip
code for context
if message.content == "-staff":
ip = requests.get('http://ip.42.pl/raw').text # Gives the "public IP" of the Bot client PC
await message.channel.send(ip)
hello, i making a youtube music bots with youtube_dl . and i got error
*** discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found**
Download ffmpeg first
you can't use a module without downloading it first
Guys, how do I get the server id in the on_member_remove event?
how?
ffmpeg python package url [https://github.com/jiashaokun/ffmpeg]
i just add it on my phyton interpenter, im using pycharm
anyone?
or that
.....
oops
🫂
python didn't delete that
wait so how i can use the ffmpeg if i hosted it?
Hosted on a VPS?
I'm assuming your VPS has some sort of package manager (if your on a linux server)
Just install it through your OS's package manager
ill host it at heroku
Heroku has a build pack for FFMPEG iirc
please help
ok so i just need to install the ffmpeg on my pc. thx for info 🙂
Forgot what the link was but you can find if you search for it
anyone?
member.guild.id @upbeat otter
thank youuu
Yw
you need to call super() on the __init__()
super().__init__(prefix)
not there
put it below your self.command_prefix = ...
and revert line 4 to the last code
async def on_message(msg):
print(msg.content)
if client.user.mentioned_in(msg.content):
emb = discord.Embed(title = "Hello!", description = "My prefix is ```sp!``` and the help command is ```sp!help```\nHave a great day!", color = 0x08bfea)
await msg.channel.send(embed = emb)```
Why is this not printing msg.content?
How can i make the bot to send the embed to the quotes channel
@visual island thanks a lot!
your code is already correct
just define quote_channel
@slate swan insert the channel id
btw its bot.get_channel(channel_id)
This is the code
ik about the bot.get_channel(channel_id) but i want when someone will setup quotes. then the bot send in the quotes channel a quote
@slate swan@boreal ravine
!e
message = "string"
if message.mention_everyone:
print("worked")
``` this obviously wont work since message has no attr mention_everyone
@boreal ravine :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | AttributeError: 'str' object has no attribute 'mention_everyone'

ik about the bot.get_channel(channel_id) but i want when someone will setup quotes. then the bot send in the quotes channel a quote
wdym
i need help
counter = 0
@bot.event
async def on_message(message):
if message.author != bot.user and message.content.startswith("!vibe"):
counter+=1```
gives me an error in counter
i need it to see that counter is set outside and change the value of it
hello, a fast question
how to remove all roles of a member?
for role in member:
await member.remove_roles(role)``` where `member` is an instance of `discord.Member`
you can do bot.counter and do bot.counter +=1 and make a command to view the counter
hi how can i make slash command with spaces? im using cogs and discord-py-slash-command.
Im using the on_member_join() event for my bot but I need the member (which is returned by default) and the guild they joined, though the guild isnt passed as a parameter
elaborate. add a print('hi') after the on_message. It will work, I am sure
not working
you just do guild = member.guild
oh thx
Ok, new question. Is there a method like Permissions.all but for PermissionOverwrites
@bot.command()
async def count(ctx):
await ctx.send(f"Number of current !vibes: {counter}")
@bot.event
async def on_message(message):
print(message.content.startswith("!vibe"))
if message.content.startswith("!vibe"):
global counter
counter+=1
print(counter)
return```
thats the code
its working the print and all, but when I try !count it doesnt work
its like on_message always works
it works, just that isnt working
put; await bot.process_commands(message) at the end of the on_message. Also, don't use global, use the method I said. It is so much easier.
how do i set the bot.counter
bot = commands.Bot(...)
bot.counter = 0
##
##
##
@bot.command()
async def count(ctx):
await ctx.send(f"Number of current !vibes: {bot.counter}")
@bot.event
async def on_message(message):
if message.content.startswith("!vibe"):
bot.counter += 1
much easier, so much easier.
you still need await bot.process_commands(message)
How can i make this a loop?
@bot.command(aliases=['setup quote'])
async def setup_quote(ctx):
quote_channel = await ctx.guild.create_text_channel(name='quotes')
await ctx.send('The channel with the quotes has been succesfully created')
await ctx.send('`*Reminder : you can move the channel anywhere you want`')
quote = get_quote()
emb=discord.Embed(description=f"**{quote}**", color=discord.Color.random(),timestamp=ctx.message.created_at)
emb.set_author(name=f"{ctx.author.name}", icon_url=f"{ctx.author.avatar_url}")
emb.set_footer(text="Next quote in 1 hour")
await asyncio.sleep(3.600)
await quote_channel.send(embed=emb)
Whats wrong here?
By using task loop.
hold on, im searching for the docs for you
ah, I have this. you're going to want to have 3 things:
a) a list of channel ids
b) a database to store the channel ids - it can just be a json file, but you probably want the bot to remember to send the quotes, even if you restart the bot.
c) a discord.ext.tasks.loop.
In this example I am going to show how you may want to do it, but I will not show it linked to a database. You can do that part yourself. My github project where I have done this is https://github.com/caedenph/jesterbot.
@tasks.loop()
async def quote():
### Get channel_ids from database here ###
for chan_id in channel_ids:
channel = bot.get_channel(chan_id)
await channel.send(quote)
in this example there is channel_ids, which holds the channel ids, and tasks.loop which is discord.ext.tasks.loop
You can also link this to a command,
@bot.command()
async def setup_quote():
#apend to database```
@slate swan you'll be able to make task loops when you understand what's going on on this page https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
@slate swan to sum it up for you. You are using a @commands.command() decorator which basically makes the function callable through a command e.i: !setup_quote not a task loop.
What you need is a task loop not a command. For this, you gotta change @commands.command() to @tasks.loop(hour = 1) and import it from discord import tasks. Then you'll have to initialize it by adding setup_quote.start() on your def __init__(self, bot): function within the main class.
😔
i wish to remove all roles of a member
but using
await member.remove_roles(role)```
but error occur because it see *everyone* too, how can skip it?
if role.name == '@everyone': continue
for role in member.roles:
if role.name == '@everyone':
continue
else:
await member.remove_roles(role)```
like that?
no, not at all. All you need to do is implement my line.
for role in member.roles:
if role.name == '@everyone': continue
await member.remove_roles(role)
continue is a keyword that makes the loop skip a loop. (It finishes the loop early)
@manic wing@potent lightthanks guys
You can do:
for role in member:
if role.is_default() is False:
await member.remove_roles(role)
both work.
Yes.
Hi hi, I'm using discord.py library, I'm currently working on a feature that checks every 10s if my minecraft server is still up and return a ping if its not, the thing is I planned to use a while loop for it but.. I can't use commands while he is looping
!d discord.ext.tasks.loop
Shall I use a thread for the loop and it works ? Or is it more than that ?
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Like this;
Oh, didnt knew about it, gonna check this
A task loop is better.
thanks a lot
@tasks.loop(seconds=10)
async def check():
#check if minecraft is up
if not up:
await Arsene.send('Oh no, its offline!')```
I'm gonna try with these tasks loop, never heard about it (im a beginner with the library) tyvm ❤️
no problem, you can pretty much do my example but add in the check for minecraft being online.
Just wanna know, can you put a global variable like seconds=timer, and if you change the timer the seconds needed will change aswell?
you can indeed
actually, to be honest i'm not sure.
I shall check.
@manic wing
@tasks.loop(seconds=3600)
async def #name of the command here?
not a command. #name of the function here
whatever you want the function name to be.
don't be.

If it can helps you, usually in Python the function name is something used to describe it shortly, with the library the name of the command is the function name if you're using the @raven peak decorator, here it's not the case
oh
The loop is just used to run something in a regular interval (for example sending a message every hour), its not a command
!d discord.ext.tasks.loop.change_interval @gaunt mortar you can use this.
No documentation found for the requested symbol.
it doesn't show up on documentation, but you can use it.
kk, thanks
I have a command foo in a group bar. is there a way to alias the command such that I can invoke it without the group name? eg ?foo instead of ?bar foo
great question. To be honest, i'm not completely sure but invoke_without_command sounds like something you might want to research.
will look into it, thank you!
im probably dumb, ive done it but i can figure it how to make it works lmao
hey so my discord bot code is starting to get very smooshed even with comments and i was wondering if i can add certain sections on the code into a different .py so for example i have 1 code called moderation.py and that was all my moderation commands and like another code called generator.py and that was generator commands but it still links into 1 bot
it just looks like its ignoring the loop
ah I forgot to say. You have to put check.start() after the loop. Sorry!
of course! Look into an amazing implementation called cogs.
standard python packages would works too nah?
ah right ill look into that
jesterbot is a discord-bot coded in discord.py with over 180 commands and 15 cogs. - JesterBot/cogs at main · CaedenPH/JesterBot
they each have the ```py
class DiscordTogether(commands.Cog):
def init(self, bot: commands.Bot):
self.bot = bot
...
def setup(bot):
bot.add_cog(DiscordTogether(bot))
instead of using @bot.command you use @commands.command. Instead of using bot you use self.bot. Instead of doing async def commandName(ctx): you do async def commandName(self, ctx):
and that is basically it
you also initiate the cog files in your main.py
bot.load_extension('filename'). Please note you do not load filename.py you just do filename.
this is often paired with py for file in os.listdir('./cogs'): bot.load_extension(f'cogs.{file[:-3]}') this loads every file in cogs dir. You might also want to consider adding an if statement to check for __pycache__, as that could raise an error.
shall it looks like smth like that or ?
@tasks.loop(seconds=1)
async def check():
print(1)
@check.start()
Cogs can:
- help with organisation.
- create auto-generated help commands.
- save time with checks and invokes for specific groups of commands.
- increase readability
- provide process_commands for on_message
Correct.
Маняци я накой да ми даде някой script за ddos
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I guess I'm doing something wrong 😄
We can't help with creating a DDoS script as it is illegal @placid jay
remove the @. I did not see it, apologies.
dw, its my bad not yours :p
Казват, че не могат да ви помогнат със сценария, защото е незаконен
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
I think you are supposed to speak english.
I think he doesn't speak english fluently, just tried to help him :p
then you can take it to dms
I created a command that does embed and after I gave an error :(
How to resolve the error?
Ok
