#discord-bots
1 messages Β· Page 736 of 1
he asked for it are you ok?
thats why im better
im the anime version of you they all love me
Lol

yeah yeah excuses
π¬ π¬

im joking its alr

no no you didnt
its just shorter lol
oh wait @spring flax dont use that thats like ctx.send yours better because your sending a response msg with interaction so thats my fault
yes
what's the difference?
if your using .send() the coro it doesnt have ephemeral but inter.response.send_message as it says responds to a interaction and does have the ephemeral kwarg so im sorry for that
i'm pretty sure inter.send(**kwargs, ephemeral=True) works too
does it?
oh yeah its a interaction attr so it probably doesπ
yeah just tried
well yes then it doesπ
also, can suggest some application user commands?
commands related to users?
an avatar command is good
and a info command (info about the account)
how do i do message commands by the way?
msg commands by?
application message commands * my bad
so like slash commands that sends a msg?
it's not on the examples on the github
well its just like any command
in this case interaction is your context which i think interaction has all of the attrs of it
I have this command and every 20 minutes it sends a new message telling me the correct time on a specific channel. How do I make it so that instead of every 20 minutes it would send a new message, it would edit the message it sent to put the new time?
@commands.Cog.listener()
async def on_ready(self):
self.current_time.start()
@tasks.loop(minutes=20)
async def current_time(self):
now = datetime.datetime.now()
now = now.strftime("%d/%m/%Y Γ s %H:%M:%S")
channel = self.bot.get_channel(914569334985216060)
await channel.send("Data atual: " + now)```
how do I DM a user with disnake's application commands?
get the id of the msg
member.send?
the arguments are
@bot.message_command()
async def bookmark(inter, message):
it's a disnake message application command
ah well i cant help much with that but probably send it to the author
!d disnake.Client.get_message
get_message(id)```
Gets the message with the ID from the botβs message cache.
Not sure but maybe message.author.send()?
nah nah
interaction has an author attr use it
inter.author.send()
its a bookmark command
so for a bookmark i suppose
import discord
from discord.ext import commands
from discord import DMChannel
mid = "550370780245000200"
bot = commands.Bot(command_prefix=".", description="Test")
@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
user = await bot.fetch_user(mid)
await DMChannel.send(user, "Test")
@bot.command()
async def replace(ctx):
return "didnt work"
mid = replace()
print(mid)
bot.run
Oh
Why doesnt my second function redefine mid
because it returns?
pass_contect typo just saying
It's pointless afaik it's set to True by default
yeah
From a channel?
no such thing
Voice ?
You could set send messages permission to false that's the only thing I can think of
RuntimeWarning: coroutine 'Command.call' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
<coroutine object Command.call at 0x000002176D2EE2C0>
await it
Huh, 100% I've seen some bots do it
is it a voice channel
You didn't await some function
Text channel
@slate swan you mean thread?


which ones should I await
if i await mid=replace than it says cant await that function
I don't see lol, you need full traceback
RuntimeWarning: coroutine 'Command.call' was never awaited
Because it's outside of async expression
Well not really, but it works with threads?
how do I fix that
I think you can remove members from threads. I'm not sure what do you mean by "kick a member from the channel". Maybe you mean mute them only in that channel?
You have to learn some serious shit
no
π¬ π¬
No nevermind, but you can remove members from a thread?
learn async programming 
It is very advanced lol
If he really needs that lol

hehe 
okay but is there any simplier I can make a command to redefine mid
Yeah I think tell me what lib you use
disnake
Btw u can't call a command like that ig
its a global var so just reassign it?
class disnake.ThreadMember```
Represents a Discord thread member.
x == y Checks if two thread members are equal.
x != y Checks if two thread members are not equal.
hash(x) Returns the thread memberβs hash.
str(x) Returns the thread memberβs name.
New in version 2.0.
how

like how would I make it a command
await remove_user(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes a user from this thread.
You must have [`manage_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_threads "disnake.Permissions.manage_threads") or be the creator of the thread to remove a user.
!e
a = "lol"
print(a)
def function():
a = "lmao"
print(a)
function()
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | lol
002 | lmao
basic py
Thanks a lot
Btw if I want to set up voting rewards for top.gg do I really need to build whole API responsible for receiving requests from them (cause I made it but maybe there's an easier method
)
import discord
from discord.ext import commands
from discord import DMChannel
mid = "550370780245000200"
bot = commands.Bot(command_prefix=".", description="Test")
@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
user = await bot.fetch_user(mid)
await DMChannel.send(user, "Test")
@bot.command()
async def function(ctx):
print(mid)
await function()
bot.run
Like it sends POST req to my API and it does the stuff
did I do something wrong
I didn't read the api yet lol
Also, how do I create a thread? I've tried looking through discord.Guild methods but can't find anything Oh nevermind, it must be a TextChannel method
πΆ
Ow recursion
Mid should be int
look down
hurts
Where

import discord
from discord.ext import commands
from discord import DMChannel
mid = "550370780245000200"
bot = commands.Bot(command_prefix=".", description="Test")
@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
user = await bot.fetch_user(mid)
await DMChannel.send(user, "Test")
@bot.command()
async def function(ctx):
int = mid
print(int)
await function()
bot.run
I am doing everything stupidly today
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: function() missing 1 required positional argument: 'ctx'
I can relate
why are you printing the int class?
Man don't call function from function
Lol I think you need to learn python first
You don't need recursion trust me also you didn't provide ctx
and why are you setting int to a var?
@dusk trout when did u learn python
Uh?
how do I get it into an async def format
class discord.DMChannel```
Represents a Discord direct message channel.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the channelβs hash.
str(x) Returns a string representation of the channel
how is setting a var value so hard
@slate swan can I know where you are from
@dusk trout please tell me what do you expect your function command to do
well so bsaically I want something like this .function 10 which redifines mid as 10
He wants it to change the value of mid ig, not sure
yes
Irdk man
You want to set mid to 10 once the function is called, right?
Maybe globals
Oh
@bot.command()
async def replace(ctx, new_value: int):
global mid
mid = new_value```
Maybe this is what you meant?
im from orsay city
@dusk trout reply to me man , when did ya learn python
oh sorry I am quite new
Where is that 
google it
Then you'd better start with smaller projects rather than discord bot
I am in bed lol
It's very complicated trust me
Yeah but I am trting to becoem a developer somewhere and this is like their minimum
so
Yeah man

good luck!
thanks π
i belive in you
All the best π
yup
Like personally I got to developing bots after getting enough knowledge about python and even after doing some stuff in pyqt 
U think to much π
β€οΈ
i love thinking 
Same π
Actually now I forgot everything about pyqt π©
i just jumped to it
Maybe I should learn it again
yeah
Me?
No
Oh lol
most people here are self thought
Don't try to learn something just because u want to learn it at the moment lol
π π
depends really
well the thing is it does redifine mid but still sends me a dm
U should learn other basic topics related to it
U got what I meant right 
yeah i did
i have the fat pika card
Can I dm ?


Can't disagree lol
does message attachments fall under message content?
Currently I want to learn AI and when I see tensorflow examples I am like wtf is this
π π
i want to learn more backend lol
π π
pretty cool
U didn't get what I meant
Nvm I don't even remember it
Ah I understand now lol
π
π©
Bye have a nice day
How do I get a list of messages in a channel? I know channel.history exists so I tried channel.history().messages but I don't think it's right or maybe I'm doing something wrong?
the stuff you're doing wrong is not checking the example in the docs
Mhmmm thanks
nope
Only the message attachments
Can anyone help me?
sure, what is it?
^ you should use this
uh
The code im trying to seperate are just async functions
well then just use cogs?
https://replit.com/@Shreyansh91/AI-Chat-Bot#index.js
idk why but my bot is not coming online e@boreal ravine
@slate swanIll take a look using cogs, never used them before π
you just have to make a class and add your commands their and you just add it
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.
bad explination so here
https://tutorial.vcokltfre.dev/tutorial/05-cogs/
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
yeah i think you can
@slate swanCan you help?
im not sure what that is but i see you sending buttons so i think you can
sure any errors?
naah
then whats the problem?
its not coming online π¦
show the code
!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.
click on this and it will redirect you
so how could i show code?
!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.
!code
@slate swan here it is
use the coding format
ok
@slate swan pic = discord.Embed().embed.set_image(url="https://toughlittlebirds.files.wordpress.com/2014/05/duckling_mallard_pieter_pieterse.jpg")
@slate swan
Hey, I've got a simple question
client.get_all_members() doesn't seem to refresh in my while loop. How can I update it's content?
so you can't help?
could you do py await ctx.author.send('direct_message')?
no
lol
okk
Uh could you show your code?
@client.event
async def on_ready():
status18 = status24 = False
while True:
for member in client.get_all_members():
# Rortox
if member.id == 575326754214903818:
status18 = handle_gpio(member, status18, 18)
# The Creator
if member.id == 395614306496020500:
status24 = handle_gpio(member, status24, 24)
time.sleep(5)
The member list and all member status information doesn't change when calling client.get_all_members
I am not sure if you really need this code construction, you could just get_user?
You're right, thanks, I'll try this
Depends on what's inside of your handle_gpio function, it should be like
status18 = handle_gpio(client.get_user(id1), status18, 18) #etc```
If your function requires Member and not User, you might want to get the corresponding instance
That's what I need, how can I do that?
Could you show your handle_gpio function if you don't mind?
def handle_gpio(member, status, pin):
# initialize status
new_status = status
if member.status.name != "offline" and not status:
print("Debug: Outputting True")
GPIO.output(pin, True)
new_status = True
elif member.status.name == "offline" and status:
print("Debug: Outputting False")
GPIO.output(pin, False)
new_status = False
return new_status
But User doesn't have a status attribute
Thanks man
@honest lintel if there's a guild they both certainly belong to, you could use
client.get_guild(that_guild_id).get_member(id1)```
to get the Member instance, otherwise
```py
client.get_guild(client.get_user(id1).mutual_guilds[0].id).get_member(id1)```
but it is more complicated and I don't think it is right way
Yes, I want to do that in a private server where both will be. Thanks, I'll try the first one.
hey @vale wing how can I make my code loop non stop
while loop
Hey @dusk trout!
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:
Like
while True: #or while 1
print('Hello')```
However infinite loops are bad practice in most of cases. What do you want to loop exactly?
bruh
?
import discord
import time
from discord.ext import commands
from discord import DMChannel
while True:
loop
?\
The better pseudocode would be
while <condition>:
#do smth```
I think
yh
Um
loop is not defined
Sorry I don't quite understand you π
^
what should I define loop as
First step of creating a code is state what do you expect your code to do
So what do you want the program to do
Use pastebin
It really matters what you loop and how you loop it in async app. If you loop sending message you will most likely get ratelimited
import discord
import time
from discord.ext import commands
from discord import DMChannel
loop =
while True:
loop
mid = "342036584650113045"
tid = "Insert Id here"
wid = "Insert ID here"
thid = "Insert ID here"
fid = "Insert id here"
suid = "Insert ID here"
satid = "Insert ID here"
bot = commands.Bot(command_prefix=".", description="Test")
@bot.command(name='dmsend', pass_contect=True)
async def dmsend(ctx):
mon = await bot.fetch_user(mid)
tue = await bot.fetch_user(tid)
wed = await bot.fetch_user(wid)
thur = await bot.fetch_user(thid)
fir = await bot.fetch_user(fid)
said = await bot.fetch_user(satid)
sunid= await bot.fetch_user(suid)
await DMChannel.send(sunid, "This is a friendly reminder to do your QOTD")
await time.sleep(86400)
await DMChannel.send(mon, "This is a friendly reminder to do your QOTD")
await time.sleep(86400)
await DMChannel.send(tue, "This is a friendly reminder to do your QOTD")
await time.sleep(86400)
await DMChannel.send(wed, "This is a friendly reminder to do your QOTD")
await time.sleep(86400)
await DMChannel.send(thur, "This is a friendly reminder to do your QOTD")
await time.sleep(86400)
await DMChannel.send(fir, "This a friendly reminder to do your QOTD")
await time.sleep(86400)
await DMChannel.send(said, "This is a friendly reminder to do your QOTD")
@bot.command()
async def replacemon(ctx, new_value: int):
global mid
mid = new_value
@bot.command()
async def replacetue(ctx, new_value: int):
global tid
tid = new_value
@bot.command()
async def replacewed(ctx, new_value : int):
global thid
thid = new_value
something like this
its goes on longer but
I want this to repeaty
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").
^
Ok, now I'm back at my first issue. It looks like client is some kind of snapshot and represents the state of the guild on initialization.
That means that the Member.status doesn't update in my program when I change it in Discord.
Is there a way to refresh the client so it contains up-to-date Member-data?
@honest lintel how do you define client?
client = discord.Client(intents=intents)
Wrong way
Use subclass of Client which is Bot:
client = commands.Bot(intents=intents)```
And better rename the variable to `bot`
Maybe that's what's causing your issue
Ok, thanks
How do I import commands?
from discord.ext import commands```
The status still doesn't update :(
That's my full code now.
import os
import RPi.GPIO as GPIO
import discord
from discord.ext import commands
from dotenv import load_dotenv
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
intents = discord.Intents.all()
description = "isOnline Bot"
bot = commands.Bot(intents=intents, command_prefix="$")
def handle_gpio(member, status, pin):
# initialize status
new_status = status
if member.status.name != "offline" and not status:
print("Debug: Outputting True")
GPIO.output(pin, True)
new_status = True
elif member.status.name == "offline" and status:
print("Debug: Outputting False")
GPIO.output(pin, False)
new_status = False
return new_status
@bot.event
async def on_ready():
status18 = status24 = False
while True:
rortox = bot.get_guild(928999025708003338).get_member(575326754214903818)
the_creator = bot.get_guild(928999025708003338).get_member(395614306496020500)
status18 = handle_gpio(rortox, status18, 18)
status24 = handle_gpio(the_creator, status24, 24)
bot.run(TOKEN)
@honest lintel the status that is not updated is member.status?
Yes. eg rortox.status doesn't change on iterations, even though I changed it in Discord.
And I think it would be a better practice to compare like
if member.status != discord.Status.offline``` iirc
using on_ready like that is a bad idea, as on_ready is called multiple times
You can always make a starting task, then end it when done
@honest lintel hold up I see what's wrong now
Ok, I'll change that
Infinite loop in on_ready which causes you to have ratelimit
You make requests to discord API too often ig
You could move it to external loop with certain interval
!d discord.ext.tasks.loop
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").
If you need usage example feel free to ask me but I think there is one
I actually debugged it and only iterated a few times over the loop, always waiting a few seconds, so I don't think this is the issue. But that's a good idea for when I'll actually use it.
Ok, thank you
Yeah waiting after each iteration is what you needed. Actually you need to use the thing I suggested, while loop in on_ready is very bad
import os
import time
import RPi.GPIO as GPIO
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
intents = discord.Intents.all()
bot = commands.Bot(intents=intents, command_prefix="$")
def handle_gpio(member, pin):
if member.status.name != discord.Status.offline:
print("Debug: Outputting True")
GPIO.output(pin, True)
elif member.status.name == discord.Status.offline:
print("Debug: Outputting False")
GPIO.output(pin, False)
@bot.event
async def on_ready():
update_online_status.start()
print("Started bot")
@tasks.loop(seconds=10)
async def update_online_status():
rortox = bot.get_guild(928999025708003338).get_member(575326754214903818)
the_creator = bot.get_guild(928999025708003338).get_member(395614306496020500)
handle_gpio(rortox, 18)
handle_gpio(the_creator, 24)
bot.run(TOKEN)
Does this look better?
Yeah, except you need to start the loop once bot is ready
Move start function to on_ready
ok
Wow, it started updating everything now! Thanks you so much @vale wing , I wonder why you're not a Helper yet
I'll do that, thanks again
That's what I was trying to do. Whenever my friend gets online, the light will turn on.
Cool! What did you do?
LEDs blinking 
Jk
I actually tried some analog input, temperature metrics and other simple projects, currently I am working on door access control system and still waiting for the materials to arrive to actually build it
The thing that might be complicated is SPI interface, that's the only I am worried about. But I hope I will be able to figure it out π
Good luck!
Thanks, good luck you too
Thank you!
@vale wing I followed your suggestion on using discord.Status.offline instead of "offline", which is a really good suggestion, but I ran into some issues. So I tried this. Do you know what is going on?
discord.Status is an enumerator
If you want to compare it with a string, you should use its name attribute
discord.Status.offline.name```
!d enum.Enum
class enum.Enum```
Base class for creating enumerated constants. See section [Functional API](https://docs.python.org/3/library/enum.html#functional-api) for an alternate construction syntax.
Iirc status inherits it
Ok, I was confused because discord.Status.offline is a String. I guess it's just some metaclass stuff going on. Thanks
!e
from enum import Enum
class MyStatus(Enum):
offline = 0
online = 1
print(MyStatus.offline == MyStatus.offline)```
Basically works like this
@vale wing :white_check_mark: Your eval job has completed with return code 0.
True
# ADD - BLACKLIST =================================================================================== Fortu'Neko#2987 ==
@blacklist.command()
async def add(self, ctx, user: discord.Member = "none"):
with open("./data/moderators.json", "r") as f:
moderators = json.load(f)
if ctx.author.id in moderators:
if user == "none":
em1 = discord.Embed(title=f":warning: Warning",
description=f"{ctx.author.mention}, you've to mention that person.",
color=col_warn)
await ctx.send(embed=em1)
else:
with open("./data/blacklist.json", "r") as f:
blacklist = json.load(f)
if user.id in blacklist:
em2 = discord.Embed(title=f":warning: Warning",
description=f"{user.mention} is already blacklisted.",
color=col_warn)
await ctx.send(embed=em2)
else:
em3 = discord.Embed(title=f":white_check_mark: Successful",
description=f"{user.mention} has been blacklisted.",
color=col_success)
blacklist = user.id
with open("./data/blacklist.json", "w") as f:
json.dump(blacklist, f)
await ctx.send(embed=em3)
else:
em4 = discord.Embed(title=f":no_entry: Error",
description=f"{ctx.author.mention}, you're not a moderator!",
color=col_error)
await ctx.send(embed=em4)
blacklist.json
Before
[]```
After
```py
123456789000```
Without `[]`, what's wrong with that?
Confusing, but thanks for helping me (again) :)
You probably assign that number to blacklist variable, but lemme look more deep into this
Yeah
blacklist = user.id```
Perhaps you meant
blacklist.append(user.id)```?
user.id is already an int
yea
Just add it to the list
Ill pay someone $5 cashapp to help me get this bot working
Also why not use @commands.has_role instead of if statement?
I don't need payment but could you show your code here?
It's more komp. for me .-.
Imho it's easier to use
also
@bot.command()
@commands.has_role(some_role_id)
async def cmd(...```
it isnt working on a role
How tho?
It's all about a userID in a json file
Oh
Yes, here it is. ```py
import requests
import json
from requests.models import ContentDecodingError
Format Sent
while True:
headers = {
'authorization': ''
}
# Request from Discord with headers
r = requests.get(f'https://discord.com/api/v9/channels/883204140279414794/messages', headers=headers)
# Print Request
jsonn = json.loads(r.text)
for value in jsonn:
message = (value['content'], '\n')
print(value, '\n')
# Discord Send Message
payload = {
'content': message
}
header = {
'authorization': ''
}
r = requests.post("https://discord.com/api/v9/channels/883204140279414794/messages", data=payload, headers=header)
break
if message == 'content':
False
Then you need a custom check, I can explain them to you
Bot with requests lib? 
I tried getting the discord library to work but it isnt for me. Do i need to do something specific to get it installed and set up :/
Could you tell me what do you expect your code to do?
Transfer messages to multiple servers
Oh so you just couldn't install the library?
No, I'm having trouble getting the most recent message to send.
So you mean send message in one server and then the bot will send it to others?
Exactly
I need it to find a specific format of content and post it to another channel
@slate swan if all the commands in the cog require author to be the mod, there's a simple trick to get rid of the if statements in every command, also it increases code readability
@hushed rain have you tried doing it with discord.py?
Or just couldn't figure it out at all
Wa
I've tried but I couldn't get discord.py to show up on my installed libraries
yeah pip install discord.py
It's just that so far, others are general
lmao xD
Oh then there's another trick π
It installed successfully?
Or gave some errors
what kind?
installed successfully, no errors along the way and all packages are up to date
def is_mod():
def subf(ctx):
return ctx.author.id in moderators
return commands.check(subf)```
im trying to install dotenv again
And then you can decorate functions with @is_mod()
And then you just can't import library?
help im stuck on trying to download dotenv
When I try running the program it says the library isn't available
who
ModuleNotFoundError: No module named 'discord'
What's your IDE
What is that ?
Code editor
visual studio code
And you run the script from there right?
Yes, from the terminal inside the IDE
Do you have python extension installed?
def is_moderator(ctx):
with open("file") as f:
moderators = json.load(f)
return ctx.author.id in moderator
@client.command()
@only.is_moderator()
async def cmd(ctx):
# cmd...
@cmd.error
async def cmd_error(ctx, error: missing.Permissions):
# cmd...
```?
why am i stuck on this
@boreal osprey try running it like this, not sure if it will help
pip install dotenv --no-cache-dir
pip install python-dotenv
Can anyone help me with replit
Not a right way
The link which we use to host isn't showing
Look at here, there's a function inside of function
I'm using dotenv, it's pip install python-dotenv
And outer function returns commands.check with subfunction as a parameter
xD
That script is coded in python
class ModOnly(commands.CommandError): pass
def mod_only():
def subf(ctx):
with open('file') as f:
moderators = json.load(f)
if ctx.author.id in moderators:
return True
raise ModOnly
return commands.check(subf)
@bot.command()
@mod_only()
async def cmd(ctx): ...```
Option with custom exception
Usually it would raise CheckFailure if you don't raise another exception
if user.id in blacklist:
em2 = discord.Embed(title=f":white_check_mark: Successful",
description=f"{user.mention} has been removed from the blacklist.",
color=col_success)
blacklist.pop(user.id)
with open("./data/blacklist.json", "w") as f:
json.dump(blacklist, f)
await ctx.send(embed=em2)
```What about that? it isn't removing
pop index out of range
.-.
class type(object)``````py
class type(name, bases, dict, **kwds)```
With one argument, return the type of an *object*. The return value is a type object and generally the same object as returned by [`object.__class__`](https://docs.python.org/3/library/stdtypes.html#instance.__class__ "instance.__class__").
The [`isinstance()`](https://docs.python.org/3/library/functions.html#isinstance "isinstance") built-in function is recommended for testing the type of an object, because it takes subclasses into account.
π€·πΌββοΈ
@slate swan list.pop removes an element by index, you need list.remove to remove the item itself
!e
help(list.remove)```
Nice protection
In this tutorial, we will learn about the Python List remove() method with the help of examples.
^ just know the difference between pop and remove for lists
https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists/11520540
thx
Np
@vale wing ty u2
Np
I'm trying to make a ping feature for a bot i'm making, but i dont know how to make it say both the latency and the string.
if msg.startswith(";ping"): await message.channel.send("In miliseconds:" {round(client.latency * 1000)}) return
F string
I need to put something in the middle and connect them, but what?
Use f string
oh yeah that exists
I've seen you have to use a + after adding the f but it doesn't seem to work. The error:
SyntaxError: invalid syntax
So there's an invalid syntax.
i guess
thank you so much
Is there a way to identify who invited a bot? I'm making a greeting msg for new users and I don't want it to greet bots (which I know how to do) but I want it to also send a msg in my staff commands saying which user invited the bot which is why I'm confused, does it work in the same way as normal member invite tracking or is there something else?
audit log?
Is this correct?
@commands.has_permissions(kick_members=True)
Is there a way to make the bot read the rest of an message after the command was sent?
oh yeah I can get my bot to read that, How do I filter that tho to get what I'm looking for as I've not dabbled with getting bots to check audit logs before
use the default discord audit
it shows who creates the bot roles and its perms
example of what you mean?
async def cmd(ctx,*,arg)
probably that, yeah
I'm guessing that's what you asking for
like to make a bot repeat something you want it to say
yeah, redd has to perfect example
ah. necessary to create a new client event?
when you do ?cmd I shat yesterday
then arg will be equal to I shat yesterday
No
yeah
So something like this
@bot.command()
async def repeat(ctx,*,message):
await ctx.message.delete()
await ctx.send(message)
Whatever you say after repeat will be what the bot repeats
correct
Hi anyone know how can i edit a embed image making a command
you have to be aware of some stuff, like this will throw errors etc if you just type ?repeat for example
Yeah
im making this code , it works in TextMessages but not in embes
@bot.command()
async def edit_gif(ctx, msg_id : int = None, channel: discord.TextChannel = None, *, link=None):
if not msg_id:
await ctx.reply(f"Tienes que agregar la ID del mensaje que quieras editar")
return
elif not channel:
await ctx.reply(f"Tienes que agregar el canal done se encuentra mensaje que quieras editar")
return
elif not message:
await ctx.reply(f"Tienes que agregar el mensaje que quieras poner para editar")
return
msg = await channel.fetch_message(msg_id)
new_embed = discord.Embed(title='\n', description='\n', color=0xff261b)
new_embed.set_image(url=f"{link}") # I try to write url=link and still don't work
await msg.edit(embed=new_embed)
if not message:
#stuff
the if stuff will never trigger / be true
any way i can set the command like !say?
most of the time i make strings with the prefix so I don't really know how it's like
Yeah just change the command name
ahh
after async def
you can have aliases...
yeah or have aliases
"Unresolved reference 'bot'"
yeah
Then change bot to client on the first line
anyone know where is the issue
please dont be stressed im just veery new lol
I'm guessing it's an invalid link, try using the link you used as an example for the embed image instead of a variable
Can I still follow this video of dbβs if I use replit? Cuz he makes a table https://youtu.be/Y9DzfPJsP2s
My discord server βΊ https://discord.gg/sfYjTSA
(If you have any questions or just want to have a chat with us)
(Some Cool Stuff)
Nertivia βΊ https://nertivia.supertiger.tk/
My server in Nertivia βΊ https://nertivia.supertiger.tk/invites/B4tMwO
Install discord.py βΊ pip install discord.py or py -3 pip install discord.py
Discord.py documentation βΊ...
can someone lmk if you're familiar with oauth2 exchange codes and how they are generated
You still can
okay, im going to try it. 
So it wonβt change anything?
Shouldn't do, no
Nothing still don't working
Show your code?
Ok ty
@bot.command()
async def edit_gif(ctx, msg_id : int = None, channel: discord.TextChannel = None, *, link=None):
if not msg_id:
await ctx.reply(f"Stuff")
return
elif not channel:
await ctx.reply(f"Stuff")
return
elif not message:
await ctx.reply(f"Stuff")
return
msg = await channel.fetch_message(msg_id)
new_embed = discord.Embed(title='\n', description='\n', color=0xff261b)
new_embed.set_image(url=link) # I try to write url=f"{link}" and still don't work
await msg.edit(embed=new_embed)
I make the command like these, for make it you need to put
!edit_gif messageID channelMention NewLink
there's no need for the link to have *, in front
because it's one word, not really a string with spaces
also, what you did in comments, please keep it like that
okay so I found the bot_add audit log action but as far as I can see it doesn't show who added the bot or am I just being dense
https://discordpy.readthedocs.io/en/stable/api.html?highlight=audit log#discord.AuditLogAction.bot_add
your link is standard a string, dont do f"{link}", that's useless
Still the same
I change it and still don't working properly
Challenge Question
How would you change the code to find the value of ['author'] inside of ['username']
for value in jsonn:
message = (value['content'], value['username'], '\n')
can you SEND the embed with the right link instead of editing a specific message? try that first
Yes i can but i want (if i can) edit the previous gif
show me a piece of json and tell me what you need, I'll tell you
i send a Embed and want to edit gif 2 min later for example
not sure if you can edit images
change this gif, if i can sure
Iterable command_prefix or list returned from get_prefix must contain only strings, not function
client = commands.Bot(command_prefix=["$", get_prefix], help_command=None)
command_prefix = get_prefix
i want a standart prefix + custom T^T
well, add that in the get_prefix function ofc
if it's not found, return the standard one
This is the terminals response
('hello', {'id': '196079195376451584', 'username': 'Ike P', 'avatar': '766de912475c7d057cb37f61f75f0f55', 'discriminator': '6874', 'public_flags': 0}, '\n')
i have a problem with using ctx. everytime i try making a command with it it doesn't work while with something like message.channel.send it works.
return prefixes[str(msg.guild.id)], "$"
```?
and what doytou need from it?
return prefixes.get(str(msg.guild.id), "$")
This is the json @potent spear π
{'id': '929143642432626750', 'type': 0, 'content': 'This Message Was Sent with Python', 'channel_id': '883204140279414794', 'author': {'id': '196079195376451584', 'username': 'Ike P', 'avatar': '766de912475c7d057cb37f61f75f0f55', 'discriminator': '6874', 'public_flags': 0}, 'attachments': [], 'embeds': [], 'mentions': [], 'mention_roles': [], 'pinned': False, 'mention_everyone': False, 'tts': False, 'timestamp': '2022-01-07T22:45:07.010000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': []}
what value do you need?
'Ike P', the 'usernames' trunk
i don't think that's working either. it just doesn't give response.
well, there's this error:
Unresolved attribute reference 'command' for class 'Client'
data = yourjsonshit
your_username= data['author']['username']
Returns
{'id': '929143461473579029', 'type': 0, 'content': 'hello', 'channel_id': '883204140279414794', 'author': {'id': '196079195376451584', 'username': 'Ike P', 'avatar': '766de912475c7d057cb37f61f75f0f55', 'discriminator': '6874', 'public_flags': 0}, 'attachments': [], 'embeds': [], 'mentions': [], 'mention_roles': [], 'pinned': False, 'mention_everyone': False, 'tts': False, 'timestamp': '2022-01-07T22:44:23.866000+00:00', 'edited_timestamp': None, 'flags': 0, 'components': []}
show me the code you tried
Actually, was able to make it work! Thank you π
{
'id': '929143642432626750',
'type': 0,
'content': 'This Message Was Sent with Python',
'channel_id': '883204140279414794',
'author': {
'id': '196079195376451584',
'username': 'Ike P',
'avatar': '766de912475c7d057cb37f61f75f0f55',
'discriminator': '6874',
'public_flags': 0
},
'attachments': [],
'embeds': [],
'mentions': [],
'mention_roles': [],
'pinned': False,
'mention_everyone': False,
'tts': False,
'timestamp': '2022-01-07T22:45:07.010000+00:00',
'edited_timestamp': None,
'flags': 0,
'components': []
}
more overview
maybe, work with indent
@-@
I was able to get it with
print(value['author']['username'],":", value['content'])
This is the solution
ofc it is
anyone can help with ctx problems? just asking
just show the code and the error, I'll tell you what's up
remember the thing redd said?
I think every can
i tried running the code
@client.command()
async def repeat(ctx,*,message):
await ctx.message.delete()
await ctx.send(message)
it didn't give a response
your client has to be defined like this
except there was this error
client = commands.Bot(...)
ah
not like this client = discord.Client(...)
commands.Bot has all the functionality discord.Client has + commands and tasks
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="$")
@client.command()
async def repeat(ctx, *, message):
await ctx.message.delete()
await ctx.send(message)
client.run("TOKEN")
``` Command would be `$repeat <message>`
@silver magnet
understood
I recommend you change the code to this to prevent people from pinging and to handle errors. @silver magnet
@client.command()
async def repeat(ctx, *, message=None):
if message == None:
await ctx.send("Arguement error")
await ctx.message.delete()
await ctx.send(f"`{message}`")
i really don't know where is the issue 
it still doesn't have input. I'm just very new to this.
Truth
your if statement will never be True, as said earlier
There
yup, that's it
is your bot in the server? ^^
it's a bot i made for a private server
I could remove triggers and send the code here
oh yeah and ofc censor the token
yeah send the code
Have you tried making sure that link actually has content in it? Because otherwise you would just be setting the image url to None.
he just has initialized his client wrong, that's all
just please dont laugh at me im veeery new lmaoo
we won't
import discord
from discord.ext import commands
import random
import os
client = commands.Bot(command_prefix=";")
TOKEN = "no"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
@client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
if msg.startswith("5naf!ping"):
await message.channel.send(f"In miliseconds: {round(client.latency * 1000)}")
return
@client.command()
async def repeat(ctx, *, message):
if not message:
await ctx.send("Arguement error")
await ctx.message.delete()
await ctx.send(f"`{message}`")
client.run(TOKEN`)```
this is on PyCharm
your on_message events are shadowing
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.
Don't use events for commands
i made that mistake before lol
never again
do py @client.command() async def foo(ctx, params): #do stuff here lol
problem is that like
ctx never worked for me for some weird ass reason
yes i have it installed
ctx, installed?
yeah
i did the pip command in terminal
im using an ubuntu based distro
just to check
don't import ctx
@silver magnet fixed
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=";")
TOKEN = "no"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.command()
async def ping(ctx):
await ctx.send(f"In miliseconds: {round(client.latency * 1000)}")
@client.command()
async def repeat(ctx, *, message):
if not message:
await ctx.send("Arguement error")
await ctx.message.delete()
await ctx.send(f"`{message}`")
client.run(TOKEN`)
omg codeblock
woww
Bot detect don't have GiF but dont change it in the embed
I put the GiF but dont change de url image of the embed
π€¨
and no idea how to solve it
tf are you using
do you even have discord.py installed
run pip install discord in cmd
Did you just install it?
yeah
but i mean
i actually installed it in the beggining of the project
that i started just today
you should update python aswell
any instructions on how to do it on linux?
show the whole command
you got the indentation wrong
@client.command()
async def repeat(ctx, *, message):
if not message:
await ctx.send("Argument error.")
await ctx.message.delete()
await ctx.send(f"`{message}`")```
that's strange, can you send all of the code and the errors your getting?
and btw did you add your bot to the server with proper perms4
client = commands.Bot(command_prefix=";")
TOKEN = "imagine the token is here"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.command()
async def ping(ctx):
await ctx.send(f"In miliseconds: {round(client.latency * 1000)}")
@client.command()
async def repeat(ctx, *, message):
if not message:
await ctx.send("Argument error.")
await ctx.message.delete()
await ctx.send(f"`{message}`")
client.run(TOKEN)```
why did it send 3 images
Can someone tell me where I'm going wrong with this, I don't seem to be getting errors but My bot just gets stuckpy async for entry in member.guild.audit_logs(action = discord.AuditLogAction.bot_add): print('{0.user}/{member} added {0.target}'.format(entry))
just f string the print
print(f"{...}/{...} added {...}")
okay well I have this now and it's erred and got stuck but it's not giving me errors or a print outpy async for entry in member.guild.audit_logs(action = discord.AuditLogAction.bot_add): print(f'{0.user} added {0.target}'.format(entry))
you don't know what an f string does obviously
you need to cover the entire text with '
even the formatentry
p sure
or i just suck
π
just remove .format(entry)
you'll be left with
print(f"{entry.user} added {entry.target}")
welcome to the wonderful world of formatting strings
anyone able to help btw?
the bot says it's running but does nothing at all
you might be running 3 instances of the bot
i mean
i think i just pressed ctrl v 3 times
lol
or are you not talking about the images
okay, well it's responding but not sending the print statement nor is it giving me a error. I'm not sure if i've done the bot_add correctly as I think it only takes target but I want to know who invited the bot
I'm talking about you running the same file 3 times possibly
huh
idk anything about that
nvm, let it be
those aren't errors btw, those are warnings
full code?
in here
ill make it a box
how are you trying to run a command?
i don't really know because i was asked to change the code to that so i didn't use events to create commands. the old script is here
so you don't know how to run a command and are asking yourself why your commands don't run? π§
bruh, you're asking the wrong questions
the way i was doing it is apparently unefficient
and in a server you're in?
this file, right?
are you 100% certain you're running that file?
PyCharm
right click anywhere in the code
then run in terminal or whatever it says
also, stop running the previous code/ bot
ill try running it in the terminal
dammit my pc overheated again
@potent spear i ran in the terminal and the result was the same. It just said it was running.
idk man
:(
#help-corn about bots
client = commands.Bot(command_prefix=";")
TOKEN = "private"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.command()
async def ping(ctx):
await ctx.send(f"In milliseconds: {round(client.latency * 1000)}")
@client.command()
async def repeat(ctx, *, message):
if not message:
await ctx.send("Argument error.")
await ctx.message.delete()
await ctx.send(f"`{message}`")
client.run(TOKEN)```
anything wrong with this code?
yeah, the repeat command will never print anything
how can i?
weird, the ping command never works
hi guys im having trouble with this snipe command ```snipe_message_content = {}
snipe_message_author = {}
@commands.Cog.listener()
async def on_message_remove(self, message):
global snipe_message_content
global snipe_message_author
await asyncio.sleep(30)
snipe_message_author = {}
snipe_message_content = {}
@commands.command()
async def snipe(self, ctx):
channel = ctx.channel
try:
embed = discord.Embed(
color = discord.Color.purple()
)
embed.set_author(name=f"Last deleted message in {ctx.channel.name}")
embed.add_field(name="Author", value = {snipe_message_author})
embed.add_field(name="Message: ", value = {snipe_message_content})
await ctx.send(embed=embed)
except:
await ctx.send("There are no recently deleted messages!")
its only executing the bottom message
I get AttributeError: 'NoneType' object has no attribute 'id' when defining guildide = message.guild.id
try client = commands.Bot(<your prefix stuff>, intents = discord.Intents.default())
that's the best I can think of
you have to except specific errors, there's a high chance that there's just an error telling you the Embed structure is incorrect
which is the case btw: the structure of your embed is incorrect
works
strange, since that's basically default...
asking again if something is wrong
client = commands.Bot(command_prefix=";")
TOKEN = "token stuff here"
@client.event
async def on_ready():
print("logged as {0.user}".format(client))
@client.command()
async def ping(ctx):
await ctx.send(f"In milliseconds: {round(client.latency * 1000)}")
@client.command()
async def repeat(ctx, *, message=None):
if message is None:
await ctx.send("Arguement error")
await ctx.message.delete()
await ctx.send(f"`{message}`")
client.run(TOKEN)```
for some reason, ctx never worked for me. Do I need to update my python?
3.6
import discord
print(discord.__version__)
1.7.3
I have this command to restart the bot and I was wondering if there was a way for the bot to send a message saying that it is back up and running in the chat that I did the command.
def restart_bot():
os.execv(sys.executable, ['python'] + sys.argv)
@bot.command(name = 'restart')
async def restart(ctx):
id = str(ctx.author.id)
if id == '543955269315723279':
await ctx.send("Estou a reiniciar... Aguarde um momento.")
restart_bot()
else:
await ctx.send("VocΓͺ nΓ£o tem permissΓ£o para usar este comando!")```
you can make a startup task, which basically does stuff as soon as the bot goes online
dpy is not downloaded i think because pip just downloaded it
but wouldn't that imply that I set a specific channel for him to send the message?
no, else, you'd have had errors whenever you tried running the code
weird
correct, that can be an issue.... since you can restart the bot from multiple guilds
you can always store the channel_id in a db, and send to that channel on startup...
This would be hard to do without a finiky method
And by finiky I mean some sort of flag passed for startup
a startup task...
Yes but then it would always send when the bot starts.
Not only after the bot gets restarted by the command
or does anyone have any idea?
well, you can clear that value in the db after the startup task
if no value was found in the db => bot doesn't have to notify anyone
So that means you'd do an API call and a database write every time the bot starts. Which can vary as discord bot's reconnect every so often to the gateway which is the connection state
nono, via a startup task, it only does this once
mhm
Yes, and so the bot can restart many times in it's lifetime
the discord py server has genius tags/commands about this subject
which is indeed described in the on_ready event
Yes, so that would mean it doesn't run only once
the startup task would only get invoked once, that's what matters ig
Yes, per lifetime
mhm

A way to do this without a database is just to make a flag, you could overwrite run to take in another arg E.g run(TOKEN, restarted=True) and do stuff with that
yeah, can perfectly be done in a config file
This would mean you need specify something else in argv
sorry if im asking too much
im just concerned because it doesnt seem to work even though everyone says it should be working
i was using the wrong prefix all the time lol
now how do i make a certain command private for a channel?
trying to make a poll feature
async def poll(ctx, *, message=None):
if message.channel == "mod-chat":
if message is None:
await ctx.send("Argument error")
await ctx.message.delete()
await ctx.send(f"@poll ping, `{message}`")
else:
return```
trying to make it only for the mods in the server
hence why the mod chat thing
The message.channel == "mod-chat" part is wrong though
You are trying to compare a TextChannel to a str
Which will never be true
You meant to check name of message.channel
The channel name.
so i need to replace message.channel with discord.TextChannel.name?
no
what do i need to do exactly?
ahhh
im still new to this, i only started like 2 days ago, can you explain if you don't mind?
since im still a bit confused
message.channel is a discord.TextChannel object, which means it has a field called name
i still don't get what exactly i need to do
i really am trying to learn from the things im doing wrong to get somewhere
Then I would suggest you start by learning a few things about basic python, such as classes
https://www.w3schools.com/python/python_classes.asp
i know the veeery basics. What do i really need to change in the code?
i think i tried it be4 but ill see
well it still detects it as str
i tried using both () and ==
if message.channel.name == "mod-chat":
...
i think ive tried that
AttributeError: 'str' object has no attribute 'channel'
it still detects it as str
i guess
oh wait a
ok then, i did not read your code completely
message is a string. It's an argument for your command, so everything typed after your command will be put as a string into it
!myexamplecommand <everything here would be put into message>
You want to use ctx.message.channel, since ctx is the object that has the actual message object
async def poll(ctx, *, message=None):
if ctx.message.channel == "mod-chat":
if message is None:
await ctx.send("Argument error")
await ctx.message.delete()
await ctx.send(f"@:clipboard: | Moderators, `{message}`")
else:
return```
is this good?
nvm, found out
Hello!
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
while True:
audio_source_list = [discord.FFmpegPCMAudio('file.mp3'), discord.FFmpegPCMAudio('clip2.mp3'), discord.FFmpegPCMAudio('clip3.mp3'), discord.FFmpegPCMAudio('clip5.mp3'), discord.FFmpegPCMAudio('clip6.mp3'), discord.FFmpegPCMAudio('clip7.mp3'), discord.FFmpegPCMAudio('clip9.mp3')]
if voice_client.is_playing():
continue
else:
voice_client.play(random.choice(audio_source_list), after = None)
await asyncio.sleep(120)
@peak loom?
This code basically picks a random mp3 clip from the list and plays it. However, the bot only uses clip3, 5, and 9. It hasnt used File.mp3, or clip2.mp3, or the others
Is there any way I can make a bot add reactions to it's own message?
Is there a way to prevent repetition unless the bot has used every clip in the list?
hm
await mes.add_reaction(":heavy_check_mark:")
You could shuffe it every time it gets through every one in the list
!d random.shuffle
random.shuffle(x[, random])```
Shuffle the sequence *x* in place.
The optional argument *random* is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function [`random()`](https://docs.python.org/3/library/random.html#random.random "random.random").
To shuffle an immutable sequence and return a new shuffled list, use `sample(x, k=len(x))` instead.
Note that even for small `len(x)`, the total number of permutations of *x* can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.
Deprecated since version 3.9, will be removed in version 3.11: The optional parameter *random*.
Interesting, would this work:
You made me have an idea.
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
await ctx.send("Argument error")
await ctx.message.delete()
await ctx.send(f"<@&role-id>, `{message}`")
await mes.add_reaction(":thumbsup:")
await mes.add_reaction(":thumbsdown:")
else:
return```
is this good?
mes would have to refer to the message sent by the bot, so you need to do this
mes = await ctx.send(f"<@&role-id>, `{message}`")
its a variable?
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
while True:
audio_source_list = [discord.FFmpegPCMAudio('file.mp3'), discord.FFmpegPCMAudio('clip2.mp3'), discord.FFmpegPCMAudio('clip3.mp3'), discord.FFmpegPCMAudio('clip5.mp3'), discord.FFmpegPCMAudio('clip6.mp3'), discord.FFmpegPCMAudio('clip7.mp3'), discord.FFmpegPCMAudio('clip9.mp3')]
audio_source = audio_source_list[:]
random.shuffle(audio_source)
for i in range(7):
if voice_client.is_playing():
continue
else:
voice_client.play(audio_source.pop(), after = None)
await asyncio.sleep(120)
@wicked atlas ?
random.shuffle just returns the list, but with it's contents in a random order. That wouldn't work because it's a list
is that why its just throwing the no messages deleted message no other error
i need to place that between mes.add and ctx.send?
This should work, let me try @wicked atlas
You might also be able to do this with the after kwarg, and some recursion
oo interesting
Yeah, I would suggest you use the after kwarg, because otherwise there's going to be a lot of unnecessary looping in the background
True, how would we go on about this?
I told you that like an hour agoβ¦
@wicked atlas I tried and it really only duplicated the message. I don't know where to place it.
@client.command()
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
mes = await ctx.send("Argument error")
return
await ctx.message.delete()
mes = await ctx.send(f"<@&role-id>, `{message}`")
await mes.add_reaction(":thumbsup:")
await mes.add_reaction(":thumbsdown:")
else:
return
Try this @silver magnet
hm
I mean, that wouldn't get you the message object
wait acually
@client.command()
async def poll(ctx, *, message=None):
if ctx.message.channel.name == "mod-chat":
if message is None:
await ctx.send("Argument error")
return
await ctx.message.delete()
mes = await ctx.send(f"<@&role-id>, `{message}`")
await mes.add_reaction(":thumbsup:")
await mes.add_reaction(":thumbsdown:")
else:
return
yep just changed it didnt see
ohhh ok alright ill go back through it
why not use channel id?
Just catch specific errorsβ¦ youβre catching all
Hey uh, that doesn't seem to add any reactions
AUDIO_SOURCE_LIST = [...]
def play_audio(voice_client, sources):
try:
source = next(sources)
except StopIteration:
random.shuffle(AUDIO_SOURCE_LIST)
sources = iter(AUDIO_SOURCE_LIST)
voice_client.play(source, after=play_audio(voice_client, sources))
play_audio(voice_client, iter(AUDIO_SOURCE_LIST))
```I might do something like this
there's probrably a better way to do it
Interesting, can you also briefly explain it a little?
but this would loop it would it?
I want it to indefinitely play the clips.
didn't change the code too
No, this would play infinitely i think
Let me try
It would iterate through the sources iterable until it reaches the end, then it shuffles it and starts again
anyone can help?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'source' referenced before assignment
i am trying to make a trigger, how do i? i tried this but i am still very new to python
async def triggers(ctx):
if ctx.message.user == "hello":
await ctx.send("hi")```
something must be horribly wrong
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
while True:
audio_source_list = [discord.FFmpegPCMAudio('file.mp3'), discord.FFmpegPCMAudio('clip2.mp3'), discord.FFmpegPCMAudio('clip3.mp3'), discord.FFmpegPCMAudio('clip5.mp3'), discord.FFmpegPCMAudio('clip6.mp3'), discord.FFmpegPCMAudio('clip7.mp3'), discord.FFmpegPCMAudio('clip9.mp3')]
def play_audio(voice_client, sources):
try:
source = next(sources)
except StopIteration:
random.shuffle(audio_source_list)
sources = iter(audio_source_list)
voice_client.play(source, after=play_audio(voice_client, sources))
play_audio(voice_client, iter(audio_source_list))
oh pff i forgot a line
AUDIO_SOURCE_LIST = [...]
def play_audio(voice_client, sources):
try:
source = next(sources)
except StopIteration:
random.shuffle(AUDIO_SOURCE_LIST)
sources = iter(AUDIO_SOURCE_LIST)
source = next(sources)
voice_client.play(source, after=play_audio(voice_client, sources))
play_audio(voice_client, iter(AUDIO_SOURCE_LIST))
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RecursionError: maximum recursion depth exceeded while calling a Python object
You can't make custom events. You can use the on_message event to make "triggers". on_message takes only one parameter, and the message class has a content attribute to return the messages content ```py
@client.event
async def on_message(message):
...
and yep im being dumb again
voice_client.play(source, after=lambda: play_audio(voice_client, sources))
well you can, you just need to dispatch them yourself
@client.on("myevent")
async def on_my_event():
pass
#elsewhere
client.dispatch("myevent")
Plays audio: But also gives this:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: Already playing audio.
Once the audio ends: We get:
TypeError: <lambda>() takes 0 positional arguments but 1 was given
this I can fix by if statement
the lambda error you can do this, i just read the docs again
lambda e: play_audio(voice_client, sources)
it passes an error as a paremeter
discord.py already covered all of discords events before it stopped development, not sure why'd you wanna create a custom event though
well, for events outside of discord's events
async def on_messag(message):
if message.user == "hello":
await message.send("hi")```
i have no idea what im doing fr
i still need to take more tutorials but its literally midnight over here
This error is caused because you have it in a while True: loop
remove that loop
oh crap didnt even realize
Anyway to timeout in After?
if you have no idea what your doing click the links below
good tutorial: https://vcokltfre.dev
dpy faq: https://discordpy.readthedocs.io/en/latest/faq.html#faq
docs: https://discordpy.readthedocs.io/en/latest/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Bc the clips play back to back, I want to timeout for 30 seconds
You can add asyncio.sleep() to the beginning of the play_audio function
ill check it tomorrow, ty
but that would prevent it from playing it for 30 secs the first time
perfect
π
dont spoonfeed and thats some real bad code
i can agree
- He's a beginner. 2) Thats not my code, i made changes to his code to make it work.
you dont give them the code
Understandable, My fault
and because hes a beginner he should be taught some good practices
e.g. using error handlers instead of making args None, etc
if your gonna make an example make it the best you can tbh

didn't know they added something called messag
you havent seen it?
it detects messag 
I have problem
when i use on_message event no command works why
even the program has no errors
@true moon dont use on_message
If you need commands, use the commands extension. Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html Why should I use the commands extension? - Prevents spaghetti code - Better performance - Easy handling and processing of command arguments - Argument type converters - Easy sub commands - Command cooldowns - Built-in help function - Easy prefix management - Command checks, for controlling when they're to be invoked - Ability to add command modules via extensions/cogs - Still able to do everything you can do with Client
I think he means that his commands arenβt working cause his on_message event
thats not even what he needs?
You should add await bot.process_commands(message) to the end of ur on_mesage
or you can just use .listen()