#discord-bots
1 messages · Page 543 of 1
try googling "how to restart a python file without shutting it down" im on mobile atm cant do much you should see a stackoverflow page
reload the COGS file
he didnt say it was a cog file
man idk whats up with this
@boreal ravine whats the pip command for utils let me try to reinstall it
then, he cant reload without cogs ig
pip install <module>
he can
i dont remember the name of it
is it discord-utils or discord.utils
!pypi discordutils
DiscordUtils is a very useful library made to be used with discord.py
@client.command()
async def ping(ctx):
await ctx.send('Pong! {round(client.latency * 1000)}ms')```
This doesn't show the bot latency... Just responds with Pong! {round(client.latency * 1000)}ms
hello
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
how to sent msg using bot
Thanks it worked
you'll have to be a bit more specific
are you using discord.ext?
is it under an event decorator?
umm
nope
i know how it come online
but senting msg
sure
cause there are many ways to have the bot send a message
ik
Import Discord Package
import discord
Client (our bot)
client = discord.Client()
async def on_ready():
# Do Stuff
general_channel = client.get_channel(877778689650200579)
await general_channel.sent('helloooooooooo')
#run the client on discord server
client.run('its my token')
see it
@stable delta see it
aight so
sent -> send
.send
but I would recommend using discord.ext instead of just discord, it's much easier to use
lol yesssss
and it provides more capabilities
ok
genus
not working
could you send your code again please but this time using a code block?
Import Discord Package
import discord
Client (our bot)
client = discord.Client()
async def on_ready():
# Do Stuff
general_channel = client.get_channel(877778689650200579)
await general_channel.send('helloooooooooo')
#run the client on discord server
client.run('TOKEN')
BOT COME ONLINE BUT NOT SENTING MSG
code blocks are using
``` before and after your code
ok
e.g.
```
print("Hello World")!
```
translates to
print("Hello World!")
ok
`# Import Discord Package
import discord
Client (our bot)
client = discord.Client()
async def on_ready():
# Do Stuff
general_channel = client.get_channel(877778689650200579)
await general_channel.send('helloooooooooo')
#run the client on discord server
client.run('TOKEN')`
You didn't add the decorator
;p;
import discord
# Client (our bot)
client = discord.Client()
async def on_ready():
# Do Stuff
general_channel = client.get_channel(877778689650200579)
await general_channel.send('helloooooooooo')
#run the client on discord server
client.run('TOKEN')```
ah I'm dumb
@client.event
I can't believe I didn't see that lol
ok
Add that at the top of your func
ok
but i am new how to do it
can you tell
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
how to do it
By learning python
I'm so sick of people like you who start with a discord bot when you clearly have 0 knowledge the language
thik se bolo
i know python
You don't
the function is the def that you put in your code
so async def on_ready() would be your function
You haven't even bothered looking at the docs, there's an example literally in the docs
print('Kraots is dump')
Kraots said to put the decorator over the function
which means you need to put @client.event on top of async def on_ready():
!d discord.Client.event
@event```
A decorator that registers an event to listen to.
You can find more info about the events on the [documentation below](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events).
The events must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)"), if not, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.9)") is raised.
Example
```py
@client.event
async def on_ready():
print('Ready!')
It's literally in the docs
¯\_(ツ)_/¯
it worksssssssssss
English
lol
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Admin\Desktop\python\real wale\my bot.py", line 9, in on_ready
await general_channel.send('@deft sphinx he i am your big fan')
AttributeError: 'NoneType' object has no attribute 'send'
now working
@client.command()
@commands.has_role("Owner")
async def giveaway(ctx):
await ctx.send("Let's start with this giveaway! Answer these questions within 15 seconds!")
questions = ["Which channel should it be hosted in?",
"What should be the duration of the giveaway? (s|m|h|d)",
"What is the prize of the giveaway?"]
answers = []
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
for i in questions:
await ctx.send(i)
try:
msg = await client.wait_for('message', timeout=15.0, check=check)
except asyncio.TimeoutError:
await ctx.send('You didn\'t answer in time, please be quicker next time!')
return
else:
answers.append(msg.content)
How do I make sudobot online?
How do i make it so the author cannot ban himself with ban command? I created something so when the author tries to do this bot sends you cannot ban yourself but now bot is banning the author and then sending the message
Run your script
if user_message.lower() == '*specs':
embed = discord.Embed(title="Sunflower Duck's PC specs", url="https://www.youtube.com/watch?v=dQw4w9WgXcQ",
description="SSD: M.2 1000GB Hard Drive MOBO: B460M Pro Vdh Wifi GPU: Intel UHD 630 Case: H510 Elite RAM: 16GB CPU: Intel core i5 10400",
color=0xFF5733)
await message.channel.send(embed=embed)
return
how do i put specsin ech rows
each rows*
use an if statement that checks if the author is the member referred to in the command
if ban_member == ctx.author:
stop()
stop() doesn't exists
Do not use events for create commands
Hello guys!
I'm using imports from discord and discord_components libraries. On clicking any button I'm getting Interaction failed error. When using buttons I don't have any ability to edit the message containing these buttons, due to how my program works. Is there a way to get around this and get rid of this error without editing the initial message containing buttons?
i want to get the author's voie channel id
No documentation found for the requested symbol.
it is this
that means they are not in a voice channel
.voice returns VoiceState so the docs won't work on it that way
You'd have to do for each individual class
.
yes, but the author.voice.channel.id is what he is looking for
Yeah
whats the package name of utils.util?
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.
!pypi discordutils
DiscordUtils is a very useful library made to be used with discord.py
i have that tho
did you read the pypi
this is the error
?
from utils.util import clean_code```
read the error theres no module called "utils.utils"
thats why im asking whats utils.util package
why are you asking me
it's your code isn't it
how am I supposed to know what module is utils.utils lol
This happens when copy paste commands, people don't even know they're supposed to copy the utils ¯\_(ツ)_/¯
¯_(ツ)_/¯
!d discord.utils.escape_markdown
discord.utils.escape_markdown(text, *, as_needed=False, ignore_links=True)```
A helper function that escapes Discord’s markdown.
@bot.command('atlas')
async def on_voice_state_update(ctx):
with sr.Microphone() as source:
ctx.send('listening...')
voice = listener.listen(source)
command = listener.recognize_google(voice)
command = command.lower()
await ctx.send(command)
@bot.event()
async def run_atlas():
if 'time' in command:
time = datetime.datetime.now().strftime('%I:%M %p')
ctx.send('Current time is ' + time)
elif 'stop' in command:
ctx.send('Shutting down...')
ctx.voice_client.disconnect()
exit()
else:
pass
await ctx.send('listening...')
anyone know why for the bot.event part the ctx and command i snot defined...?
nvm i go tit
!d discord.on_voice_state_update
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
what does self.view.embed.description.split("\n")[0] do?
that's extremely specific question, im gonna assume embed is a discord.Embed object, embed.description returns str, so str.split returns a list based on the str from the given param as the discriminator, which is newline, so [0] is gonna get the first element of that list
Lol
guys i need some help rq
I was making a server prefix command then I ran into a slight issue
def get_prefix():
paths = os.scandir("servers")
for path in paths:
return
client = commands.Bot(command_prefix=getprefix(), intents=intents)```
my server directory saves the ids of guilds, how exactly to I send a guild object or id to my function.
`Note: i'm not asking about how to give my function arguments i already know how to do this`
example code to understand what im trying to find here
def get_prefix(guild):
paths = os.scandir("servers")
for path in paths:
if path.name == guild.id:
return
client = commands.Bot(command_prefix=getprefix(guild), intents=intents)```
if command prefix is callable discord.py expects it to take 2 parameters: bot and message, so you make that the function signature and use message.guild
thanks!
Oh and remember about dms; guild may be None
??
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
embed = discord.Embed(title="muted", description=f"{member.mention} was muted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
await ctx.send(embed=embed)
await member.add_roles(mutedRole, reason=reason)
await member.send(f" you have been muted from: {guild.name} reason: {reason}"
How to make it so the owner can access this code
*can use this code
if ctx.author == ctx.guild.owner: **rest of code**
tysm
np
wait
ok
in the if statement?
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
if ctx.author == ctx.guild.owner:
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=False)
embed = discord.Embed(title="muted", description=f"{member.mention} was muted ", colour=discord.Colour.light_gray())
embed.add_field(name="reason:", value=reason, inline=False)
await ctx.send(embed=embed)
await member.add_roles(mutedRole, reason=reason)
await member.send(f" you have been muted from: {guild.name} reason: {reason}")```
@gloomy quest dont spoon feed lol
thx
what about adding reactions? And how to make it so that when reacted, it would do something?
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@velvet tinsel
Okay so, my check function is not working as intended, its supossed to check if a message was sent by the orginal author
def check(m):
return m.author == message.author
try:
msg = await client.wait_for("on_message", check=check,timeout=15)
except asyncio.TimeoutError:
await message.channel.send("Took too long to response")
return
else:```
Ik the reason why its not working, something to do with `m.author` not being the proper attrbute or smth in `return m.author == message.author`. I just have no clue how to fix this.
and this isn't exactly helping
you should wait for "message" not "on_message"
^
is there a list of events like that?
a valid event like on_message or on_reaction_add or on_message_delete works, just remove the on_
hmm
Basically all events
yeah, your custom event also works
Yes
If you look a lil' in the docs you'll find them listed on after another
im not
and dont ping for not answering
Where can I promote my friends server
Definitely not in this server
thanks carrot
yw
I still dont get how to use "DISCORD_SLASH" module. It seems does not work at all
did you read the docs first? or the examples?
Yes still doesn't work
Hey @astral fossil! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
from discord import Client, Intents, Embed
from discord_slash import SlashCommand, SlashContext
bot = Client(intents=Intents.default())
slash = SlashCommand(bot)
@slash.slash(name="test")
async def test(ctx: SlashContext):
embed = Embed(title="Embed Test")
await ctx.send(embed=embed)
bot.run("Oof")
from help_command_embeds import ...
wait no
no i want to import the function from main.py
you can't
dag nabbit
cycle import error thing
ack. can i use the sys module tho?
for?
import it
from main import function
but that gave me an error
whats the error?
Detected discord.Client! It is highly recommended to use commands.Bot. Do not add any on_socket_response event.
idk i just heard that sys helps with importing
Never seen that error before
Me too
@errant shuttle
um i cant find it anymore 😦 lemme try and remake the error. please wait
ok.
discord_slash doesn't allow you to pass discord.Client instance, use commands.Bot
@boreal ravine it is for custom prefix command
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/runner/Efendo-Bot-SRC/server.py", line 11, in run
app.run(host='0.0.0.0',port=8080)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/flask/app.py", line 920, in run
run_simple(t.cast(str, host), port, self, **options)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/werkzeug/serving.py", line 1010, in run_simple
inner()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/werkzeug/serving.py", line 950, in inner
srv = make_server(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/werkzeug/serving.py", line 782, in make_server
return ThreadedWSGIServer(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/werkzeug/serving.py", line 688, in __init__
super().__init__(server_address, handler) # type: ignore
File "/usr/lib/python3.8/socketserver.py", line 452, in __init__
self.server_bind()
File "/usr/lib/python3.8/http/server.py", line 138, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.8/socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use
172.18.0.1 - - [18/Oct/2021 12:20:22] "GET / HTTP/1.1" 200 -
Which do i replace with commands.bot
you're using threading module for your bot?
NO
bot = discord.Client()
idk why i am getting that
show code
this doesnt relate to an import?
Good news, it doesn't show error but so with the slash command on tab
root/main.py
from nextcord import *
from nextcord.ext import commands
def get_prefix(client, message):
with open('prefixes.json', "r") as prefix_file:
prefixes = json.load(prefix_file)
return prefixes[str(message.guild.id)]
client = commands.Bot(
command_prefix=get_prefix,
strip_after_prefix=True,
case_insensitive=True,
)
I also added an (underscore) init file.
root/modules/help/embeds/embed.py
from main import get_prefix
idk why i am getting that
what IDE are you using?
Ah.
show your server.py
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "Webste for bot"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
It never gave me this error before
use a proper ide replit gives import errors sometimes
ack but i dont have moni to buy vps 😦
i didnt say anything about a vps
then? i wanna make it 24/7 online
Is this from that YouTube vid about making ur bot online 24/7
yep
👋
it works for me too...
Oh ok
how do u do that
a command?
like i make a random 3 digit number
yes
Can someone help me? My hole bot and all functions just stopped working, I tried without the on)message event and still nothing works
and the user shud reply the same number , then it shud verify the user
show code
use the random module
Its like 3000 lines
i use it
Error?
Theres no error
from discord import Intents, Embed
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
bot = commands.Bot(intents=Intents.default(), command_prefix='??')
slash = SlashCommand(bot)
@slash.slash(name="test")
async def test(ctx: SlashContext):
embed = Embed(title="Embed Test")
await ctx.send(embed=embed)
bot.run("lol")
It doesn't show error but it still don't show slash command
just nothing works
then the problem?
but what i mean is like a verification system
just show one of the commands
like react role?
you need a guild_id thing if you don't have that it's gonna take an hour for it to appear
@bot.listen()
async def on_message(message):
if message.author == bot:
print("Hi")
else:
global author_msg_counts
author_id = message.author.id
curr_time = datetime.datetime.now().timestamp() * 1000
if not author_msg_times.get(author_id, False):
author_msg_times[author_id] = []
author_msg_times[author_id].append(curr_time)
expr_time = curr_time - time_window_milliseconds
expired_msgs = [
msg_time for msg_time in author_msg_times[author_id]
if msg_time < expr_time
]
for msg_time in expired_msgs:
author_msg_times[author_id].remove(msg_time)
if len(author_msg_times[author_id]) > max_msg_per_window:
await message.channel.send(f"{message.author.mention} is gemute ivm meervoudig spam.")
role = message.guild.get_role(861384357758238740)
await message.author.add_role(role)
if message.content in blacklist:
await message.delete()
await message.channel.send(f"{message.author} Dat woord is niet toegestaan.")
if message.author.bot == False:
with open('json/users.json', 'r') as f:
users = json.load(f)
await update_data(users, message.author)
await add_experience(users, message.author, 5)
await level_up(users, message.author, message)
with open('json/users.json', 'w') as f:
json.dump(users, f)```
Nuts
u have listen() but your using the event in the function name?
I guess
process commands
Doesnt fix it either
y
is there an error?
Nope
noo like a verify thing where u do verify cmd and the bot dms u message (the random 3 digit number) and the user shud send that random in the bot's dmsdigit number and the bot gives the verified role
you dont process in listen
because you need to process commands when you're using messages in on_message
**n o **
you dont need to do that in .listen()
listen is ddifferent to event
So it automatically appear after an hour?
oh he's using listen my bad
yes or read the docs on how to use the guild_id thing
But how do I fix it then 👀
Ok
@ionic wadi idk how listen works but isnt it like this?
@bot.listen("on_message")
u should use @wooden frigate
oof
why?
Its not an command
its an event
and I use bot
like a verify thing where u do verify cmd and the bot dms u message (the random 3 digit number) and the user shud send that random in the bot's dms 3 digit number and the bot gives the verified role
Random number generator, save that to a variable and make the bot wait_for a response
and then check if message.content = variablename:
Code
else:
Code
how to integrate a embed in a listen command?
Just as normal?
yes but how haha
why u telling me?
z
um you shud use databases for a random number for each user and the number shud be 8 digit
File "/home/container/bot.py", line 155, in <module>
@bot.event()
TypeError: event() missing 1 required positional argument: 'coro'
Whut
it is @bot.event not @bot.event()
what?
Instead of activity=activity()
its a module error
its not
hm
nextcord.ActivityType then?
yes
hm
How can my bot check if it has permission to send message in that particular channel??
!d discord.abc.GuildChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
And you can put as argument Guild.me
this dont work. Pls help
What doesn't work
typehint to int
Just saying "this don't work" won't help
no error in cmd idk whats wrong
Do you by any chance have an on_message event?
And as kylee said, type hint the argument to an int

you cant have check on events..
The @commands.has_role doesn't work for events
Remove it
And you're missing await bot.process_commands(mesage)
should i just put this in the event?
you can just do @bot.listen()
You can get rid of the event anways
so you don't need process_commands
yeah
wow
I want to learn
me too
How to check if the bot has send_message permission in a specific channel
I need a code teacher Tell me from starting @slate swan
Bro Check her role
And perm
bruh
?
I want to do it within code
@slate swan
Try it and see, we're not your interpreters ¯_(ツ)_/¯
@slate swan what is all cmd of making a bot bassic cmd
!d discord.abc.GuildChannel.permissions_for
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
This function takes into consideration the following cases...
Returns permissions
Then you'd need to look at
!d discord.Permissions.send_messages
Returns True if a user can send messages from all or specific text channels.
Hi
can you help me in my bot
post your code here
tts = gtts('hello bostike logo')
tts.save('gandu log luvde')```
not working
when i am offline
You trying to do a Text to speech thing?
it didnt work in offline
idk how to do it offline but you can definitely do tts without needing gtts
yessssssss tell me
i am making alexa
I thought it was to a discord channel.
Off memory, it's simply "channel.send("message", tts=True)"
channel can also be ctx
nope
not in bot
only in python
interpreter
didnt we tell you to go learn python yesterday
😮
it works now. thank u 🙂
Hi
How?
No worries.

python
who knows. But whatever it is, it's not discord bot related.
UMM with discord vc?
from playsound import playsound
playsound('helllo.mp3')
a=(input('type code:'))
if a == 'help':
print('1 = google')
print('2 = text into word')
print('3 = play song')
else:
print('type ?Help')
a2 = input('type command:')
if a2 == '1':
a3 = input('type website name:')
import webbrowser
webbrowser.open(a3)
else:
print('wrong statement')
if a2 == '2':
text=input('type here:')
from gtts import gTTS
tts=gTTS(text)
tts.save('byee.mp3')
from playsound import playsound
playsound('byee.mp3')
else:
print('wrong command')
if a2 == '3':
from playsound import playsound
playsound('song.mp3')
print('playing song.')
print('playing song..')
print('playing song...')
print('playing song....')```
look code
try it
need only = gtts
WOW
module
google tts?
take gtts module
May I use your code?
in module
sure
Like telling something..
THNAKS!
I like this ```py
if a2 == '3':
from playsound import playsound
playsound('song.mp3')
print('playing song.')
print('playing song..')
print('playing song...')
print('playing song....')
No delay in the "playing song" so it'll print all 4 of those at the same time lol
but you need learn how to use it
I hope you make a cool bot
lol
can i send a DM?
not a bot
Umm I'll maybe google it
Sry
lol nope
Use time.sleep(0.1)
it is a ai google and alexa
Cool
I was thinking about making an interface so I could send messages to a channel as my bot xD
I wanna do it too
i will tech you can you share screen
Dont speak to me like that. you dont know me that way

Sus
Slash command is depressing is a fact
does someone have an event so the bots status shows how many servers the bot are in?
There are no events like that
something else?
Make your own task loop
do you have one?
im not that good yet
Is it really that hard?
what's with the scribbles mate?
does that show in console how many servers the bot are in?
@bot.command()
@commands.is_owner()
async def showdiscords(ctx):
print(bot.guilds)
await ctx.send(bot.guilds)
output is:
[<Guild id=794837147068792862 name="Gnomeslayer's server" shard_id=0 chunked=True member_count=4>]
Up to you to figure out the rest
Nice code
:) cool
If expanded upon, you could turn bot.guilds into an object and extract the id's and get other stuff.
Create an entire embed as well
how to get infos from a message of a user message into the bot ?
What do you mean ?
when a user send a message i want too grab the nummbers or text
change it to a string
no you. i simply created the base for something to be worked with
hm
you know what i mean ? @drifting arrow
yeah. i believe it's like "ctx.content" or something.
alright thanks made
how do i start my task in a cog bot event on_ready
Like a loop?
no
commands.Context has no attr content
well. idk then. i havent touched bots in a while. Thought I'd sit here for fun
hm
ctx is sent if it's part of a message. so you could do something like ctx.content or ctx.message.content
If it's in response to everytime a message is sent you'd need to do something different
^
i've written a task.loop in a cog , i want it to start in my main file, using on_ready
Don't start it in on_ready
@commands.Cog.listener()
async def on_message(self, ctx):
isbot = ctx.author.bot
if isbot == False:
messagecontent = ctx.content
messageattachments = ctx.attachments
if not messagecontent:
await ctx.channel.send("Please attach some text.")
else:
await ctx.channel.send(f"Message content: {messagecontent}")
if not messageattachments:
await ctx.channel.send("Please attach an image.")
else:
await ctx.channel.send(f"Message content: {messageattachments}")
``` here is something I wrote a while ago to do something
useless variable
fite me.
and that param can be whatever i write.
i guess so
i believe documentation says "message"
no
i'm calling it only once though
Bruh
If you want a loop to start when a cog is initialized you can just run it in the __init__ part of the cog
init function yes
def __init__(self, client):
print("[Cog] Loops has been initiated")
self.client = client
self.con = sqlite3.connect('bot.db')
self.autounmute.start()
#print("Started the autounmute function with an interval of 10 seconds.")
This is what I use for my auto-unmute function
i've got a variable that is in the main file, which is why i wanted to start it in main
Just keep your main discordbot file empty with nothing but the necessary code to load the bot
Then change it as a bot variable so you can use it anywhere
Move everything to cogs.
im kinda new, can you explain how, thanks
!d discord.Embed
😮
By bot variable I mean, if you defined ur commands.Bot as bot, and the variable is something, change it to bot.something, this will allow you to use the variable in any file you want
!botvat
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
There's a tag now (:
Anyone have discord music bot code
how do i make a var with server members count
!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)
Thanks a lot
!d discord.Guild.member_count
property member_count: int```
Returns the true member count regardless of it being loaded fully or not.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Anyone have discord music bot code
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)
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Ok
script kiddy?
"I'm a hacker"
lmao
hm
no_pm=True means cmds won't work in dms right?
yeah
whats no_pm though
I think it's no private msg
you can do commands.guild_only
nice, thanks
Does it have to be in specific order?
Cool
@dense swallow below the command decorator
no
the actual way would be above it
@commands.command(no_pm=True)
```??
but it doesn’t matter with dpy
is no pm a thing?
hm
It's not??
dude can you read, kayle told you to use commands.guild_only
Carl bot uses it in it's code (outdated)
really
In GitHub
ok its outdated
@dense swallow @hasty iron
Yeah I saw it from there
I asked if it ever existed
this is python server
not javascript
🗿
Sry
api banned lol
read the error
you kidding me ?????? why
who knows
read the error
you’re probably spamming the api in some way
Too many requests.. it says there
literally says "too many requests"
😦
🙁
it only lasts an hour dont worry
Were u re running ur bot many times?
hm
in most cases it’s an hour
public host?
cubic
oh
i cant host on replit
Why?
replit isn’t a host
I just use it because my bot is not so big
Khmm you say any?
.....

hehehe
wot
What nowww not work hostt 😭
Oh I remember something,
I made a bot which sends a particular message to all the channels....but the problem is that in some channels it does not have send_messages permission and so it stops executing whenever it encounter such channel....is there a way to bypass the channel...I tried using try except but pass just skip the loop and return does nothing....
what about the face 😶
what?
can someone help me?
send_message
say
i have a bot
ok next
The bot sends message
the bot is coded to answer to a message with an manual input
yes
except discord.Forbidden:
pass
```:)
screen
like that:
with open("token.txt", "r") as file:
token = file.read().replace("\n", "")
import asyncio, discord, time
prefix = ">"
client = discord.Client()
@client.event
async def on_message(message):
nachricht = input("Message: ")
await message.channel.send(nachricht)
client.run(token)
and
u cant use input function
I used py except: pass
but it terminated the loop
in discord
try to dont use a bare exception ig
ok trying
like that(message was defined in console)
but it stops working after the second message
I dont think you can use input there
^
for rp
rp?
cuz im dumb
role play
....
I can see you're a beginner and client.wait_for would be too much
so idk
Instead use py await message.delete()
it will delete your message and send the message
for what
unbanned for lastes hour?
whats your point?
i used the message from me as sample
yes
bro you're banned for API spamming probably, just wait an hour
Just I mean, The owner send the message and the bot will delete it and send the copy of the message
does he want that though
the message from bot are trough console
how hour correct?
just a suggestion
what
my block lasts for about 12 hours :(
just wait lol
how many hour sorry?
then you really did some stupid shit ig
i dont know but probably> 24 hours
<
oooooooo
Nah
<
I dead bye
i want to use the bot like this https://www.youtube.com/watch?v=23jCFhEyPoI
It ends badly.
Discord hackers are the most powerful beings to exist. Full power, complete control... nothing gets in their way.
╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
╠╗║╚╝║║╠╗║╚╣║║║║║═╣
╚═╩══╩═╩═╩═╩╝╚╩═╩═╝
follow these for a chance to be in my next video!
• Twitter - https://twitter.com/beluga1000
• Instagram - https://instagram.com/belug...
above 24 hours?
below
!e
e = 10
if e > 24:
print(1)
if e < 24:
print(2)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
2
hm
kayle....
!e print(5>6)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
False
See
yeah that's what I said!
thats what i said though
I SAID THAT
hm
uh ye
so what's the part that doesn't go
on_guild_join event
the bot crashes
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
maybe thought of that??
so it gives you no output at all?
it crashes after the first message
the bot send
it goes offline?
pick a random channel or whatever you want from Guild.text_channels and send a message to it
yes
huh
you would use it like any other event
huh what
you dont even have an on_ready event or something like that
that’s a bit contradictory
there are lots of troubles with this but nothing should crash the bot
you already have an event listener inside your code
it should be simple to know how to use it
...
@slate swan its like making a function but its async and has a decorator
i have never used an event -> i have an event -> i have some events
so you did nothing
and you have no clue what to do
are you learning python or just how to use dpy
then why are you using dpy
dpy is not for beginners
you should learn more python before using discord.py
do you understand the concept of decorators
then learn more python
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I learned dpy first and I know lots of shit about dpy and not so much about py
and it's a bad feeling
so don't do that
no, kayle
nah bro i dont wanna learn python for 5 months just to send a message to a discord channel
the answer is no
💀
wow speedrunning any%?
lmao actually speedrunning knowledge
@bot.event is a decorator aswell
anything that starts with @ is a decorator

dosent work.
Somone pls help.
It also can be used as an operator
errors?
no
defining an asynchronous function
@bot.listen()
async def on_message(message):
if not (message.author == bot.user) and ('hi' in message.content.lower()):
await message.reply("Hello")
Why it isn't pinging the user?
Never heard of a @ operator
Thought so
it's not there
Isn't working
example?
Well it only pings the bot
Since you have an if that checks if the message is by the bot
!e ```
print(1 @ 2)
@hasty iron :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: unsupported operand type(s) for @: 'int' and 'int'
Oh wait ignore that
wow
it is an operator(?)
Didn’t see the not
@ not for ints?
no clue
That’s a decorator not an operator
!e print("e" @ "e")
@boreal ravine :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: unsupported operand type(s) for @: 'str' and 'str'
i just wanted to test it
It checks if the message isn't sent by the bot
Operators are == != etc
https://stackoverflow.com/questions/6392739/what-does-the-at-symbol-do-in-python/28997112#28997112
it calls object.__matmul__
it doesn't show on thingy
Yeah haha I missed the not part
hm
but I just learned about some stupid shit
I was under the impression w3schools was a bad resource
it isnt
it just doesnt have a "detailed" explanation on everything
yes
just like the dpy docs
realpython is useful for me
that’s actually interesting
I'm really worried about it now
Well where else are you going to learn in depth about it d.py?
what
it's gonna ruin my day once
source dpy code
they are just an API reference
The dpy docs serve both as quick reference and in depth information
yeah that's why
Personally I have trouble finding any good resources other than the GitHub and the reference
well you don't really need more than github, stackoverflow and the docs
Stack overflow is meh everything there is outdated for dpy from my experience
SO is so outdated
No
no
if they were the same why would they both exist
No
Events are for events, commands are for commands
^
bot.command() is called whenever a message starts with your prefix and continues with the function name
function name?
You must've never used the name kwarg before
or the name kwarg
bot.command is not the thing that’s called everytime a message is sent or whatever, it’s the callback of the command
I know about it but I actually haven't
¯\_(ツ)_/¯
nop
symbols in a command I find cursed
The name of the command.
hm

it does nothing
!code please use this
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.
u did pass
placeholder
its an example..
it indicates you should put something there by yourself
can someone fix my bot pls
no
sure
bot = bot.Commands (Commands_prefix ="-" this is entirely wrong
pretty sure this channel is for asking for help
what is that
i need help fixing my bot who can help me it has collab
bot = commands.Bot()
"missing one required positional arg" 
thanks for correcting me, I had trouble with this for 2 hours man
command_prefix
thank you Tsekis
lmao
/sarcasm
@slate swan cool badge sir

so i made this bot and
if ctx.message.author.id == 872976347369201765:
on repl
is it safe to leave the tokens around like that?
nope
or should i move my code to visual studio code
use env , a tab named secrets in replit
thats more preferable
Hi 
are u good with python?
you didn’t finish your kick command
fix your indents, it's messed up
also don't use replit
can someone help me it has collab i dont understandddd
e my friend coded it not me 😭
im trying to learn python but its hard
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
eee
can u join my collab and fix it for me plssss
you can't always have others fixing things for you you gotta try to fix it yourself
i tryed thou
No
but i make it worse E
that's why we're here
kk
plenty of people here to help out
i did but i made it worse
But you can ask for help here, not for spoonfeed
convert memeber to something that is serializable
i.e a name, ID, something like that
afaik the json library allows you to serialize your own objects by subclassing it, don't remember 100% so you'll have to read into it
EEEEEEEE i did ask for help but i dont understand what ppl tell me so i just ask if they can do it so i cann see and i will know how to fix it thats how i learned a bit from my friend
You need to learn python first
well then you should learn basic python if you don't understand
can i send u photos and u can help me fix the problem?
You can paste code here or in a pasting site
!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.
!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.
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix = "!")
@bot.event # the bot event decorator
async def on_ready():
print(f"{bot.user} is online")
@bot.command() # bot command decorator
async def ip(ctx: commands.Context):
await ctx.send("ult8.falix.gg:39318")
@bot.command() # bot command decorator
async def UltraFact(ctx: commands.Context):
await ctx.send("Ultra was helped by an awsome dude named AceyGoBoom to make this amazing bot")
@bot.event
async def on_message(message):
if message.content.startswith("hi"):
await message.channel.send("hello")
elif message.content.startswith("water"):
await message.channel.send("is drinkable 😏")
await bot.process_commands(message)
@bot.command()
async def avatar(ctx, member: discord.Member):
embed = discord.Embed(colour = discord.Colour.blue())
embed.set_image(url = member.avatar_url_as(format = "png"))
await ctx.send(embed = embed)
@bot.command()
@command.has_permissions(administrator=True)
async def ban():
await ctx.guild.ban(member)
await ctx.send(f'User {member} has been banned')
@bot.command()
@command.has_permissions(administrator=True)
async def kick():
bot.run(os.environ['Token'])
@untold moon error?
File "main.py", line 46
bot.run(os.environ['Token'])
^
IndentationError: expected an indented block
ur command
@untold moon again saying, you need to learn python first.
is empty
where
You will not understand 90% of what we may say unless you learn basic python
lmao
E
^
Good decision
Hello, could someone give me the code to write so that a bot can delete a certain number of messages from a command because i can't?
no
why can you not?
tell us the part that doesn't go well
what's stopping you from figuring out how to do it on your own
params
I wrote this (with the token at the end) but nothing happens ... I also tried something else which also doesn't work :/
from discord.ext import commands
bot = commands.Bot(command_prefix="b!")
@bot.event
async def on_ready():
print("The bot is ready!")
@bot.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)