#discord-bots
1 messages · Page 475 of 1
can you send your code
Windows for daily use and gaming and Linux for programming and wasting your life trying to figure out issues on stackoverflow
Do you need all of it?
that was the full traceback.
usually thats not the full error when you run your code and that error pops up
He’s using pycharm so I’m pretty sure thats the full error?
@jolly glacier @hasty iron Code, as requested:
https://paste.pydis.com/koqobiqeka.py
Thx
No, it's not that
My token is definitely valid (it's been used in test scripts)
and it is passed in identically
Maybe regenerate your token?
i dont think what you sent is the full traceback tbh
I’m inputting the code into repl
I could send you a screenshot, if you wish - I guarantee you that's the entire traceback that I see in the console
okay send a ss
He is using pycharm, usually pycharm doesn’t like dealing with tracebacks
there is nothing on top of that?
as you can see, that's all I have :p
I’ve got to head out for a little while bye, hope you figure out a fix
I have the PyCharm run configuration stuff, plus a debug print message
thanks!
can you run your code outside pycharm
Exactly the same.
(just without the highlighting)
and [SESSION ENDED] is just my debug message that gets printed after bot.run()
do you have a WSL
yep
can you try running it there
sure, ill setup a venv
(Also, with some more digging, PyCharm debug tells me that the exception happens when discord.ext.commands.Bot.start() is called)
hm
oh wait
the docs say, start is a combination of login and connect
you have only login
just call super().start(*args, **kwargs)
...i think i figured it out, yeah
pycharm actually helped pagman
well, it works now
Thanks a lot for helping!
i really am nothing without my traceback huh
what/who's pagman
a twitch emote
ah i got it 
how to make commands cooldown and send a custom message?
!d discord.ext.commands.cooldown
discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.on_command_error "discord.on_command_error") and the local error handler.
A command can only have a single cooldown.
If a cooldown is triggered, then CommandOnCooldown is triggered in on_command_error() and the local error handler.
!d discord.ext.commands.CommandOnCooldown
exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after)```
Exception raised when the command being invoked is on cooldown.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
if i want an arguement to be 2 words, like a single arguement
how do i do that
@bot.commands()
async def test(ctx,arg1,arg2):
pass```
here i want arg 1 to be of 2 words
when passing the argument you can do <prefix>test "this is arg1" arg2
guys could you please help i dont know what this error means
Is it possible to make two different cooldowns on a command for different roles? So one role has a cooldown on 30 seocnds but the other role has a cooldown on 15 seconds
can you read your error?
Guys what is better Ipc or Api
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Guys what is better Ipc or Api
both accomplish different things
you cant compare them or say whats "better"
@hasty iron what is better for dashboard
most people use ipc for dashboards to communicate with their bot
@hasty iron ipc isin't working with me lol
I am not even able to connect to the backend
ur using discord.ext.ipc?
Only getting a freaking error
Yes
ive seen somebody on the discord.py server saying to use zmq rather than that for IPC
Lol now wth is ZMQ
Wait a sec how th can it help me
it can be used for ipc
For ipc or in replacement of ipc?@hasty iron
what
Guys, how do I display the time when the message was sent to embed? Discord.py
how do i fix this?
@commands.command()
@commands.is_owner()
async def saran(self, message, ctx, *, args):
channel = self.bot.get_channel(887908566382571580)
await channel.send(f"{message.author.mention} saran: {args}")```
it works but the problem is, when i run this command, it will send the second argument
example
input: hello world
output:
world
why do you have message, ctx
message is for ping the author of the message
message.author.mention
and the ctx?
ctx is ctx?
ok so what are those two doing there
wait it is the same?
normally, a command has its first argument as?
ctx?
wait so message is the same as ctx?
ctx is Context and message is Message
thanks!! i got it

so no one needs help rn 
bot.user is None here , could you show more of the code?
bot.user is None when the bot isn't logged in
Guys, how do I display the time when the message was sent to embed? Discord.py
define your lavalink client after bot is ready
i am not sure what this client_secret is but as the name suggests it seems to be something that should not be leaked and you have done just that.
mhm
ohh, thanks
!d discord.Embed.timestamp this is what you need ig
The timestamp of the embed content. This could be a naive or aware datetime.
Can you please tell me what to write here?
delete "pass"
hello
i have a question do discord can bots play songs from spotify
or its against discord tos like youtube ?
Whatever you want
I've never used Spotify api so idk what the secret does but id suggest reuploading the image without the credentials
Just in case
if anyone knows sqlite3 pls come to #databases
Does anyone know why this does not work?
await ctx.send(embed=random.choice(errormsg)).delete(delay=4)
``` the msg gets sent but it doesnt get deleted after the delay, why?
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, file=None, files=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/stable/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed "discord.Embed") and it must be a rich embed type.
delete_after=4
what forks yall using 👀
so uhh im making a custom prefix command for my bot, and i have this code which uses json to store the data. im not using json, instead im using mongodb. can someone help me convert this code to mongo? im guessing its gonna be similar since mongodb uses BSON
with open("prefixes.json") as f:
prefixes = json.load(f)
default_prefix = "!"
def prefix(bot, message):
id = message.server.id
return prefixes.get(id, default_prefix)
are you sure youre not using json 🤔
im looking at pycord though they don't have slash command support for cogs yet
pycord. rn i moved back to d.py cuz i had some probs with heroku, but gonna update soon
0of use https://pypi.org/project/disnake - it has slash commands for cogs already and i love how its implemented!!
Surely worth a try
i said this code is for json. i want to convert it to work with mongodb
pycord alpha has it, but its pretty fucked up rn, so im not gonna use slash commands at the time being lol
async def play(ctx, url):
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
URL = info['formats'][0]['url']
voice = ctx.author.voice.channel
try:
await voice.connect()
except:
pass
voice_client = ctx.guild.voice_client
await ctx.guild.change_voice_state(channel=voice,self_mute=False, self_deaf=True)
voice_client.play(discord.FFmpegPCMAudio(URL))```
its start to play and suddenly stop
https://discordpy.readthedocs.io/en/latest/
a slash command would be ```py
@commands.slash_command(name="test", description="idk")
async def test(self, ctx: discord.Interactions):
await ctx.response.send_message("Hello")
that simple
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
hmmmm
pls help
wait
i have better code one sec
ok yes i frgt
so youll need to define the stuff
wait one sec

pip install pynacl
thx :)
pip install pynacl in shell
then restart ur IDE
@valid galleon
you can watch this video https://www.youtube.com/watch?v=rE_bJl2GAY8 to learn the basics of pymongo
and then switch to motor using this https://gist.github.com/anand2312/840aeb3e98c3d7dbb3db8b757c1a7ace
motor is preferred for pymongo and discord bots as it is async
alright i'll try to code it now
How can my bot play playlists from spotify in VC?
im trying to do that the bot takes a random image from a site and sends it to the channel but it says syntax error on embed
@client.event
async def waifu(self, ctx, arg): embed = discord.Embed( title = 'waifu',
description = 'waifu', colour = discord.Colour.purple())embed.set_image(url= "websiteurl.format(arg)) embed.set_footer(text="")")
await ctx.send(embed=embed)
lets not talk about the name btw
help
you could try praw(which uses reddit to get the images)
its pretty easy to use too
ok thanks praw is a module ?
yeah, but asyncpraw is recommended since its faster
ok i can get any random image with it ?
Use the JSON API of reddit if u want to just get the memes
yeah you can get a random image from the specified subreddit
praw is better imo
ok thanks
easier to use as well
@slate swan https://youtu.be/Q5u6MDQAG7I this should help
convert the code to asyncpraw once it works
how to make my bot join a server via invite?
||illegal||
!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)
u can't ig
people od it
get an invite for the bot from the discord developer portal. you can use the link infinitely. it wont expire
Thank you so much
lol how the person who invites needs invite perms
you cant make it join using a command, but you can make it return the invite link once you run the command(as a hyperlink)
np
it does use d.py
huh
its a very simple command. just make an embed and put the hyperlink in it
saw what ?
i have made my bot online using replit now how do i bring it back to offline without changing the code
use a kill command?
you’ll need to change the code though
Im pretty sure there is an stop button on the screen on repl it
you just hit that and your bot goes offline
i mean its fine unless its not much of a major code change
i ll see that
thank you
np
- click stop
- make a command and do
await client.closeor something i forgot
i m not sure why but your replit looks different from mine @round yarrow
there is no stop button aswell
can ya tell me why
it gaved me this error
Traceback (most recent call last):
File "C:\Users\guest\Downloads\bot.py", line 5, in <module>
reddit = praw.reddit(client_id = "XXXXXXXXXXX",
TypeError: 'module' object is not callable
why is my replit different from yours
praw.Reddit
different themes?
i dont have a stop button either
and they are using a web server to keep their repl running 24*7 so a webpage appears
yeah i noticed it now sorry
you have one on your sidebar ig
hacker plan ig
replit gives free hosting
means you kinda have a server in replit. but not exactly
wheres the stop button tho?
its a terminal so press ctrl + c
@bot.command()
async def coinflip(ctx,message,message1):
await open_account(ctx.author)
users = await get_bank_data()
user = ctx.author
if message1 is None:
await ctx.send("Please Type how much you are Gambling.")
money = message1
if random.choice(determine_flip) == message:
embed = discord.Embed(title="Toss", description=f"{ctx.author.mention} Flipped coin, YOU **WONN**! {money} coins")
users[str(user.id)]["Wallet"] += money
await ctx.send(embed=embed)
else:
embed = discord.Embed(title="Toss", description=f"{ctx.author.mention} Flipped coin, YOU **LOST**!")
users[str(user.id)]["Wallet"] -= money
await ctx.send(embed=embed)
with open("bank.json","w") as f:
json.dump(users,f)```
isn't showing any error but not working
any idea what's wrong
Hello. I am taking input from the user as : value, first unit and second unit. I want to convert the value from the first unit to the second unit, any idea how will I do that, the units can range from anything
wym convert from first to second? Can I know what type of command u wanna make?
ah
I made one but it is specific to certain units. I need to make it for all units or most of them.
You will have to convert yourself
I don't think there is a way to do so in dpy
u can see the math lib if there is something
!d math
This module provides access to the mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.
message1 is a required argument so it will never be None
what part isnt working
Yeah but even if i remove that part the code won't work
how check if bot play something now?
!d discord.VoiceClient.is_playing
is_playing()```
Indicates if we’re currently playing audio.
any reason why the msg doesnt get deleted?
await ctx.send(embed=random.choice(errormsg)).delete_after(4)
await ctx.send(embed=random.choice(errormsg)), delete_after=4)```
it keeps saying await is out of function and i added a : and it said invalid syntax how do i fix it?
em.set_image(url = url)
await ctx.send(embed = em)
show full code
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
bruh, thanks
show full the function

@client.commmand()
async def animeme(ctx):
subreddit = reddit.subreddit("Animemes")
all_subs = []
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
check indentation
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
i did
all_subs from that line its out of the function
ok
@client.command()
async def animeme(ctx):
subreddit = reddit.subreddit("Animemes")
all_subs = []
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)```
thanks but now it says that client isnt defined in client.command()
do i have to import something to use client.command?
no
ok
wait there is triple m in command
it says the same thing?
@client.command()
import discord
import time
import praw
reddit = praw.Reddit(client_id = "XXXXXXXXXXX",
client_secret = "XXXXXXXXXXXXXXX",
username = "XXXXXXXXXXXXXXXXX",
password = "XXXXXXXXXXXXXXXXX",
user_agent = "XXXXXXXXXXXXXXXX")
@client.command()
async def animeme(ctx):
subreddit = reddit.subreddit("Animemes")
all_subs = []
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
lmao
add this after 3rd line also from discord.ext import commands``````python client = commands.Bot(command_prefix=">", help_command=None)
ok
How can I do this?
Bot Description from Dev Portal
thanks but how do i active the command
ahh thank you
It's already invoked
wdym?
Just run the bot and try the command lol
thats the thing how do i try the command😭
ok ok
import discord
from discord.ext import commands
import time
import praw
import random
client = commands.Bot(command_prefix=">", help_command=None)
reddit = praw.Reddit(client_id = "XXXXXXXXXXX",
client_secret = "XXXXXXXXXXXXXXX",
username = "XXXXXXXXXXXXXXXXX",
password = "XXXXXXXXXXXXXXXXX",
user_agent = "XXXXXXXXXXXXXXXX")
@client.command()
async def animeme(ctx):
subreddit = reddit.subreddit("Animemes")
all_subs = []
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
client.run("your_token_here")```
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
once again
what are you trying to do
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
next time try it in #bot-commands
Oh yeah I forgot
didnt do anything
i put the prefix and it didnt do anything
!d discord.ext.commands.Command.signature
signature```
Returns a POSIX-like signature useful for help command output.
!d inspect.signature
inspect.signature(callable, *, follow_wrapped=True, globals=None, locals=None, eval_str=False)```
Return a [`Signature`](https://docs.python.org/3.10/library/inspect.html#inspect.Signature "inspect.Signature") object for the given `callable`...
Blanket is faster and got a better keyboard.
it uses that
no lol, i have a membrane
Do you mean I don't? 
I have a $5 keyboard , poor 
also if you still dont understand that, you can go and mess around with it a bit
I'm trying to add a reaction w discords rest api but it shows method not allowed json, is the endpoint wrong or smth?
This is my code
requests.post("https://discord.com/api/v8/channels/866260548714627073/messages/888086722573910052/reactions", headers=headers, json={'reactions':['✔️']}).json()
the error is pretty clear no?
the HTTP method is not allowed for that route
which is POST
i put the prefix and it doesnt execute the command and it doesnt show a error?
import discord
import time
import praw
from discord.ext import commands
client = commands.Bot(command_prefix = "$animeme", help_command = None)
reddit = praw.Reddit(client_id = "XXXXXXXXXXXXXX",
client_secret = "XXXXXXXXXXXXXXXXXX",
username = "XXXXXXXXXXXXXXXXXXXX",
password = "XXXXXXXXXXXXXXXXXXXX",
user_agent = "XXXXXXXXXXXXXXXXXXX")
@client.command()
async def animeme(ctx):
subreddit = reddit.subreddit("Animemes")
all_subs = []
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
are you actually running the bot
yes
Isn't adding reactions supposed to be a PUT request???
And you would need to add authorization headers seems like you are already passing headers
oh right, and also its better to have a single requests session (i think)
is that all your code?
yes
and use asyncpraw cuz praw is blocking
Would be better to use discord.Route cz why not haha
discord.Route and request session are two WHOLE different things

discord.Route doesn't even make a request
its discord.http.Route
It represents an endpoint
where?
wdym where
nah nvm
anyways can you add an on_ready event inside your code, print something there, and rerun your code and see if it prints
also
are you sure you're invoking the bot correctly
me cuz if it is yes it does print
yes i am
didnt do anything
errors?
nah i think i have the problem i put:
client = discord.Client()
client = commands.bot
i should put a 2 in second client right?
thats like, way way different from what you sent earilier
oh sorry
give me a sec
when streaming audio from a url can you do before_options={'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 1'} in discord.FFmpegPCMAudio? because i do this and i can get it to reconnect after it breaks or smth
can i do this?
1.
client = commands.Bot
client = discord.Client()
or
client = commands.Bot
client2 = discord.Client()
No why
client = commands.Bot()
do this ^
You are generally recommended to name the instance bot
bc the instance Client is used for user accounts
i did in my code
which if you do use it for a user account u will be banned from discord
What 
but who said anything about selfbots
can i do option 2 tho?
No what
No, either create Client or Bot
No lol
ok so only 1 client
im not smort 🧠
Yeah but I will recommend using Bot
ok i will
thank you
can you pls help me
when streaming audio from a url can you do before_options={'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 1'} in discord.FFmpegPCMAudio? because i do this and i can get it to reconnect after it breaks or smth the audio stops before its acualy finished
thats weird
maybe just close the tab
and then the bot stops working...unless uk you have a third party hosting service or have used flask to host it or maybe have replit hacker
a url to a mp3 file on discord
you forgor the open at thr line file = ('ignore.txt' 'w+')
hey is there any other way other than replit + uptime bot to host my bot for free.. for some reason it goes down
Any free hosting can't guarantee you a reliable uptime
But you can try heroku for learning
hmm
thank you i don't know how i not saw it
May I know why did you use CSS syntax highlighting and not Python?
just for beauty
!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.
Python's would make it much better.
python is prettier
msg_dump_channel = 886496848196542514
ignoreusers = []
@bot.event
async def on_message(message: discord.Message):
channel = bot.get_channel(msg_dump_channel)
file = ('ignore.txt' 'w+')
file.write (int(message.author.id))
if message.author == bot.user or int(message.author.id) in ignoreusers:
return
if message.guild is None and not file:
iduser = message.author.id
nameuser = message.author.name
text = message.content
embed = discord.Embed(title = "Личные сообщение бота: ", description = (f"css\n{ text }"), color = 0x1f8b4c)
embed.set_footer (text =f"ID автора: {iduser} | Ник автора: {nameuser}")
embed.timestamp = datetime.utcnow()
await channel.send(embed = embed)
await bot.process_commands(message)
lol
CSS makes only websites pretty, not Discord messages!
hm.
any libraries i can use to play music for le bot (besides ytdl)
when streaming audio from a url can you do before_options={'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 1'} in discord.FFmpegPCMAudio? because i do this and i can get it to reconnect after it breaks or smth the audio stops before its acualy finished
like local files?
discord mp3 links
not you lol
oH ok ty
can someone please help me
with
this
try it and see
i have
hundreds of times
many different combinations
it still stops playing the sound middle of it and no errors happen
could be something with discord
i doubt it
like 100% boubt it
is there any way to active some sort of debug mode for ffmpeg that spits out infomations no matter what
im sure there is
because if there is then the hundreds of google results i have looked throu are dumb and will never work because i have spent the last 7 hours trying to get it to not stop in the middle
How exactly are you "streaming audio from a url", what kind of URL is it and what do you use? Do you use pytube, youtube-dl or anything of those sorts?
discord mp3 url
send a mp3 in chat
not good harddrive
delete the file after its been played
bruh what
ur computer surely cant be that bad
sounds like its infected
nah im joking not downloading the mp3 files tho
if not self.persistent_views_added:
self.add_view(SelfRoles(), message_id=888129416193007706)
self.persistent_views_added = True
```this is in on_connect ^^^
```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/-2/owner.py", line 546, in on_connect
self.add_view(SelfRoles(), message_id=888129416193007706)
AttributeError: 'owner' object has no attribute 'add_view'
```help???
what is owner
my cog
a cog doesnt have an add_view method
why
Is there a way to make my bot do ctx.send when it is shutting down
like when it goes offline or do I have to say it?
on_disconnect event (can be called multiple times)
Thats for dcing a vc?
So where i have my on start i would put under that
on_disconnect
await ctx.send("Bot is going down!")
wat
discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_connect "discord.on_connect") call.
@client.event
async def on_disconnect():
...``` Tho ctx.send won't work in ``client.event``
I would put @bot.event
Thanks
👍
wait rq how would i make it send a msg?
hmm
!d discord.ext.commands.Bot.get_channel
get_channel(id)```
Returns a channel with the given ID.
Actually I am facing the same problem as you.. I am asking help in another server and waiting for a response
oh lol
why not ask here lmao
cuz there is much better
just cus i made a bot that im only running on my pc for reasons and want a event to show its shutting down
the dpy server?
They are very good in pycord
lofma
isnt that the other shit fork
Can I run a coro with bot.loop.run_until_complete?
Oh
bot.run calls loop.run_forever
loop.run_until_complete requires the loop to not be running
Hmm
since discord.py is stopping someone made something called pycrod... So similar to discord.py
use loop.create_task instead
Ah ok
pretty good 1
Well I want to run the async function in the init of the class
I'm pretty much predicting someone will take dpy over
you could do the run_until_complete
eh...
but when you reload the cog (via command) it will raise an error
I'm just gonna wait and see
If they will they probably would said in the past
assuming you load the cogs before you start the bot
So I should use create_task and be on the safe side?
yeah sure
Oh cool
is it allowed if i can ask a question on how to create a queue for my music bot?
class PaginatorView(discord.ui.View):
def __init__(self, ctx, pages: Pages, embed, timeout, show_page_count):
super().__init__(timeout=timeout)
self.ctx = ctx
self.pages = pages
self.embed = embed
self.show_page_count = show_page_count
self.children[5].disabled = True
if self.pages.cur_page == 1:
self.children[0].disabled = True
self.children[1].disabled = True
def lock_bro(self):
self.children[5].disabled = True
if self.pages.cur_page == self.pages.total:
self.children[0].disabled = False
self.children[1].disabled = False
self.children[3].disabled = True
self.children[4].disabled = True
elif self.pages.cur_page == 1:
self.children[0].disabled = True
self.children[1].disabled = True
self.children[3].disabled = False
self.children[4].disabled = False
elif 1 < self.pages.cur_page < self.pages.total:
for b in self.children:
b.disabled = False
!paste dude
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
its not disabling ```py
@discord.ui.button(disabled=True,label='Skip to page...', style=discord.ButtonStyle.blurple)
async def numbered_page(self, button: discord.ui.Button, interaction: discord.Interaction):
#lets you type a page number to go to
if self.input_lock.locked():
await interaction.response.send_message('Already waiting for your response...', ephemeral=True)
return
if self.message is None:
return
async with self.input_lock:
channel = self.message.channel
author_id = interaction.user and interaction.user.id
await interaction.response.send_message('What page do you want to go to?', ephemeral=True)
def message_check(m):
return m.author.id == author_id and channel == m.channel and m.content.isdigit()
try:
msg = await self.ctx.bot.wait_for('message', check=message_check, timeout=30.0)
except asyncio.TimeoutError:
await interaction.followup.send('Took too long.', ephemeral=True)
await asyncio.sleep(5)
else:
page = int(msg.content)
await msg.delete()
await self.show_checked_page(interaction, page - 1)
Dude
its not that large
It has covered my whole screen....
oh
cheers
(:
is it allowed if i can ask a question on how to create a queue for my music bot?
YTDL is against ToS, so I am afraid not allowed
hey guys im new in coding and i want to create a bot i dont want him to do anything he should just stay online and print current game nothing more can someone give me the code and how i can run it i already create a application at the dc dev portal
Is there a way to store additional data in a view/button, to recall in future when the button is clicked? I don't want to have to create a "dummy button" to hold that info
what do you mean by "print current game"?
oh, OK, I see
so you want it to display an activity in its profile
exactly
cool, I can do that
import discord
client = discord.Client(status=discord.Status.online, activity=discord.Game(name="VALORANT (replace this string with whatever)"))
client.run("YOUR_BOT_TOKEN_GOES_HERE")
@sudden sage this dead simple script should work
New question/elaboration; if I store data in the view subclass, say like this:
class MyView(discord.ui.View):
def __init__(self, data=None):
super().__init__(timeout=None)
if data is not None:
self.data = data
Does that mean that data would be saved, even for persistent views?
should i create an folder in visual studio code or where should i type this code in
Just run that Python code, however you normally run your code.
As long as you have the discord.py package installed, it'll work
which IDE should i use?
which IDE would you use
i am trying to use webhook
But when someone voted this will pop up, how do i fix this?
use an F string
I wouldn't use an IDE for that
I'd just run the Python script as-is
in this you can most definitely use a F string
as i said im new in it so where should i type this code in
you have to parse the data before posting the webhook then. What are you sending the webhook from?
Normally there should be a user here somewhere, but it's not there?
Have you never used Python, at all? In that case, a couple of quick dead basic questions:
- What is the output of
python -vwhen ran in the terminal? - What operating system are you using?
nah bro i just create an print("Hello World") thats it
im currently on windows
and as for question 1?
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
Error reading or writing history file 'C:\Users\my naem\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt': Access to the path is denied.
um
erm why did i get this
is this related to discord
mhm so how do i fix it
also ```async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'Hey':
await message.channel.send('Shalom, how is it going?')``` why doesnt this work? it worked before
intents = discord.Intents.default()
intents.members = True```
show the whole code
hello guys
Therefore you do not have Python installed.
- Go to https://python.org/
- Download Python 3.9.7 (shown in screenshot)
- Run the executable
can anyone help me please?
hello!
dont ask to ask
from discord.ext import commands
#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.command()
async def clear(ctx, ammount=10):
await ctx.channel.purge(limit=ammount)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'Hey':
await message.channel.send('Shalom, how is it going?')
client.run('token')``` @kindred epoch
???
i did
do you have the @bot.event decorator?
that's not a Discord bot issue, that's just a permission issue. You're trying to read or write to a file you aren't allowed to.
hm weird
on_message is an event, so you have to use @bot.event or @bot.listen() as the decorator. Thats not in a cog so you dont need self as a arg
help please
First things first, it's __init__, not __innit__. You'll have to fix that for it to work.
Next up, lines 9-17 are over-indented.
Ok thanks
also, please be patient - people need time to type out a response to your solution.
error is pretty clear, if you know enough python you should be able to fix it by yourself
i'm learning python
c'mon, that's not really helpful, considering this is a server for helping with learning Python
yea...
that does not even relate to #discord-bots
so i opened python
- Run the command
python -m pip install discord.pyin the terminal - Create a file with the
.pyextension - Paste in the code
- Edit the necessary values
- Run the file
SyntaxError: invalid syntax
what?
it shows up
when running the file?
i did the 1st thing
I don't get it lol
run it in the terminal, not in Python
right now it shows up Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
You're sending the wrong data, you want to actually resolve/evaluate the user ID somehow. How you do that depends on your workflow
what are you coding in?
That shouldn't be happening, you just installed it, right?
I am trying to create a webhook
yeah, try that
still
yes, I have no idea what you're sending that from, but you need to replace user with the actual user ID
how you do that depends on you
Normally there should be user here but it is not there?
Find Python in Windows search, and right-click and choose "Open File Location"
then send the full path to that folder
Maybe this?
how do you check if a msg has a embed or not? it's just py if message.Embedsright? and then if I wanted to get attributes out it would be py message.Embed[0].description[0]
I would love some help learning how to make this bot better. This bot is for educational purposes only. I'm just trying to learn how to program with asyncio and discord libraries better. https://pastebin.com/QW0iwSW6
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
rn if i want to paste the code it shows The command "import" is either spelled incorrectly or
could not be found. @jagged hamlet
You have both client = discord.Client() and bot = commands.Bot(...
it's one or the other. I would stick with bot.
Did you paste it exactly as-is?
yea
Screenshot?
what's wrong with line 3?
you shouldn't use tydl, it's against TOS
whos TOS?
youtube's
the error comes from line 19 in file music.py
this guy is your ytd also?
the decorator should be aligned in indentation with the function definition
look at line 19
and look at line 21, the line after a function definition should be indented
ok
your next function is outside of the class, you need to indent it to have it inside
wait no it's not
your first two are inside of the init
uh
@full lily any advice on how to make the bot dc from voice after the sleep? i tried running it in it's own thread. I also tried to make the sleep asyncronous but i muck up the hearbeats
where am I looking? what line
106 is commented out
i cant include it at 168, it disconnects immediately
i cant include it where it is, that part is threaded and seperate
how i can remove this
threading does not mix with asyncio
sure it does, im currently doing it
how would i restructure what im doing though, to make it better
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)``` doesnt work?
hm i might be thinking of something else
that code i posted works... just badly
it doesnt dc after the file is done transmitting
so i know i built it janky and hacky
im trying to fix that I need to learn
EY HELO ME MAYBE?
...
@slate swan your behavior makes me not want to help you with the limited knowledge I do have
im trynne get help i gtg soon sry
bot = commands.Bot(command_prefix='?', description=description)
@bot.command()
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)
try that tho
We can possibly help you if we know what the problem is.
command doesnt work
instead of calling it a client
Any errors?
nop
what it is doing?
So. I want to make a command called status. And I was wandering if could take some things from a game called "FiveM" or "GTA RP". I would like it to say if the server is online and how many players are in the server. Is this even possible??
nothing
@slate swan if they include a api sure
to check if the server is online, you can ping it. If you get a response it's online
@slate swan there is nothing in the console?
from discord.ext import commands
#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.command()
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
word_list = ['Hore', 'faen', 'Faen', 'hore', 'fitte', 'Fitte', 'fuck', 'Fuck']
# don't respond to ourselves
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
word_list = ['Hore', 'faen', 'Faen', 'hore', 'Fitte', 'fitte', 'fuck', 'Fuck']
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("No DLL's allowed!")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("No EXE's allowed!")
else:
break
client = MyClient()
client.run('token')``` here is the code
@slate swan well your token isnt "token"
i kno
and you need a bot, not a client
File "main.py", line 3, in <module>
import music
File "/home/runner/Music-Bot/music.py", line 19
@commands.command()```
how to fix
and it's this part of the error
i would use bot instead of client
i couldnt get client to work either
@slate swan you are trying to censor people?
ok i dont support censorship, so im done
bro its for a esport thing
it has 10 yo kids in it man
i dont care at all what the use-case is lol
?
not a valid reason not to help someone
it's his choice and he's asking for help
I mean they do have an API but I think it is not supported with python. So I can't right?
you can hook their api with requests if they support an api
jesus just stop being a brat
sure ur against it but there is 10 year old kids
do u want them to start saying racist shit
hm?
i think it's their right to do so yea
👀
you cant be pro free speech and then get mad people say stuff you dont agree with
It's not that he doesn't agree, it's not letting people ruin other people feelings and put them down
ok this gone too far anyone else wanna help me?
look im not trying to get political, there are other people here
political? this a python server to get help
sure since they other guy is not
First of all, you want to create a bot instance. Not a client instance.
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)``` this line doesnt workj
It's not that line.
you can just tell them to read this instead: https://vcokltfre.dev/
Yeah that's true
I dont think they are going to help man, they dont wanna help youtube download bot makers
is there a module named "music" that you downloaded?
Oooh
are you trying to import a cog o_O
its for a music bot
that doesn't answer the question but if it is a cog you don't need to import it, if it's a library you need to download it first via repl's package manager
i said read what he said
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You're not in voice channel")
voice_channel = ctx.author.voice_channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
@commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_stramed 1 -reconect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, dowload=False)
url2 = info['formats'] [a] ['url']
source = await discord.FFmpegOpusAudio.from_proble(url2, ++FFMPEG_OPTIONS)
vc.play(source)
@commands.comand()
async def pause(self,ctx):
await ctx.voice_client.pause()
await ctx.send("Paused Music")
@commands.comand()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Resume Music")
def setup(client):
client.add_cog(music(client))
what do i read there is nothing to read about !clear
how to make it so that when sending a message to a private message on behalf of a bot player, the bot should check in a text file whether its id is in the text file and if the code found its id in the text file "ignore.txt", then let the bot just start ignoring it
in this code:
msg_dump_channel = 886496848196542514
ignoreusers = []
@bot.event
async def on_message(message: discord.Message):
channel = bot.get_channel(msg_dump_channel)
if message.author == bot.user or message.author.id in ignoreusers:
return
if message.guild is None and not message.author.bot:
iduser = message.author.id
nameuser = message.author.name
text = message.content
embed = discord.Embed(title = "Личные сообщение бота: ", description = (f"css\n{ text }"), color = 0x1f8b4c)
embed.set_footer (text =f"ID автора: {iduser} | Ник автора: {nameuser}")
embed.timestamp = datetime.utcnow()
await channel.send(embed = embed)
await bot.process_commands(message)```
@slate swan yo, do you just wanna get something up and running, or do you want something that you are building on top of?
you check for bot twice by the way. Or is there a diff between the two?
from discord.ext import commands
from discord.utils import MyClient
#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.command()
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)
class MyBot(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
word_list = ['Hore', 'faen', 'Faen', 'hore', 'fitte', 'Fitte', 'fuck', 'Fuck']
# don't respond to ourselves
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
word_list = ['Hore', 'faen', 'Faen', 'hore', 'Fitte', 'fitte', 'fuck', 'Fuck']
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("Er ikke lov med .dll")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("Er ikke lov meg .exe")
else:
break
bot = MyBot()
bot.run('my token cant be bothered to change after this so dont mind the token it self :)')```
whats wrong witht hte !clear command?
It might be
i install visual code
or help you learn
just fix, bc learn is hard

bc its a link
@slate swan dm me man, that way other people can learn here
ok, wait i will open my dm
done
Is anyone familiar with linking stock market data to a bot? Not sure where to go to grab info such as the top gainers in premarket.
i know y'all are supposed to help with coding but is there any good ways to get bots into servers
how to make it so that when sending a message to a private message on behalf of a bot player, the bot should check in a text file whether its id is in the text file and if the code found its id in the text file "ignore.txt", then let the bot just start ignoring it
in this code:
msg_dump_channel = 886496848196542514
ignoreusers = []
@bot.event
async def on_message(message: discord.Message):
channel = bot.get_channel(msg_dump_channel)
if message.author == bot.user or message.author.id in ignoreusers:
return
if message.guild is None and not message.author.bot:
iduser = message.author.id
nameuser = message.author.name
text = message.content
embed = discord.Embed(title = "Личные сообщение бота: ", description = (f"css\n{ text }"), color = 0x1f8b4c)
embed.set_footer (text =f"ID автора: {iduser} | Ник автора: {nameuser}")
embed.timestamp = datetime.utcnow()
await channel.send(embed = embed)
await bot.process_commands(message)```
ok thx
i can't even use top.gg cuz my phone number is blacklisted 🙄
@commands.cooldown(1, 3, commands.BucketType.user)
@commands.command(aliases=['colorme', 'colourme', 'color'], usage="`tp!colorme <color>`")
async def give_color(self, ctx, *, role: Creamy = None):
"""Allows users to give themselves a color role. do `tp!colors` to see what you can add to Yourself
If there arent any colors, do `tp!rainbow` to create the roles"""
with open('colors.json', 'r') as f:
data = json.load(f)
color_roles = [discord.utils.get(
ctx.guild.roles, name=x) for x in data]
if role is None:
m = await ctx.send("Okie, starting to remove your roles..")
for x in color_roles:
if x in ctx.author.roles:
await asyncio.sleep(0.5)
await ctx.author.remove_roles(x)
await m.edit(content="Role(s) removed.", delete_after=delay)
elif role in color_roles:
await ctx.author.add_roles(role)
await ctx.reply(f"Alright, {role} was given.\n**Reminder, if you want to remove your colors, just run `tp!colorme` just like that to remove them!**")```
how could i check if the user already has a role before adding a new one?
check which roles the user has, if they said to give the role they already have then send something else
or maybe it just raises an error
idk
@slate swan bots as in fake users to join your server?
or bots as in helpful bots that carry out functions
if current_server == guild.id: what are you trying to do here
on_member_join passes member not ctx
huh
bots as in a discord bot made in discord.py
not like tokens
Can someone help me to make a ban counter on one specific member
?
Im on a server dat a person gets ban like 99 times a day so we whant to make a counter for it
huh
a person cant get banned 99 times on the same server
unless they unban him and then ban him again
but we un ban him
why do you do that then
for fun
hey 13 year old beginner to coding, I'm coding a dc bot rn and it's not working
can someone help?
what's the issue
I'll just send the code
you can listen for an event on_member_remove i think
off the top of my head
and then check if the member was the person you're looking for
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
await bot.process_commands(message)
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('compliment me'):
await message.channel.send('u suck')
if message.content.startswith('LOL'):
await message.channel.send('licking oversized lameasses')
if message.content.startswith('Compliment me'):
await message.channel.send('u suck')
if message.content.startswith('insult me'):
await message.channel.send('u suck')
if message.content.startswith('lol'):
await message.channel.send('licking oversized lameasses')
if message.content.startswith('Im so cool'):
await message.channel.send('no your not, fuck you')
if message.content.startswith('Hello'):
await message.channel.send('no one likes you loser')
@client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
client.run('this is where my bot token is, it's correct, double checked it multiple times')
!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.
but do you know what's wrong?
format your code like above and i'll have a look
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
await bot.process_commands(message)
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('compliment me'):
await message.channel.send('u suck')
if message.content.startswith('LOL'):
await message.channel.send('licking oversized lameasses')
if message.content.startswith('Compliment me'):
await message.channel.send('u suck')
if message.content.startswith('insult me'):
await message.channel.send('u suck')
if message.content.startswith('lol'):
await message.channel.send('licking oversized lameasses')
if message.content.startswith('Im so cool'):
await message.channel.send('no your not, fuck you')
if message.content.startswith('Hello'):
await message.channel.send('no one likes you loser')
@client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
client.run('this is where my bot token is, it's correct, double checked it multiple times')
your on_message is inside your on_ready
and also process_commands need to be inside the on_message
so you’re still a python beginner?
lol
i suggest you learn the language first
what
so just gimme instructions and boom
??
yea, no thats not what we do
It's called a joke, but mb
serious thing -> question -> "its a joke bro"
but anyways
you should really learn python before making a discord bot
???
discord.py is a hard library for beginners
maybe
case in point
you have any recommended starter projects that aren't simple games like snake or hangman
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
does anyone know what i did wrong? i know discord_component changed some stuff but it’s showing errors
!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.
Could you please send your code and the error in a message instead of an unclear screenshot?
what do you think?
!d discord.Guild.premium_subscribers
premium_subscribers```
A list of members who have “boosted” this guild.
I believe it will require some intents
like this?
Don't send a screenshot. Copy the code and the error and send them.
ok.
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
not sure what interaction library etc ur using
this is the error i get whenever i try the urban command
how can I check how much users have a certain role?
!d discord.Role.members
members```
Returns all the members with this role.
use that with len()
ahhh thanks!
np
how to make it so that when sending a message to a private message on behalf of a bot player, the bot should check in a text file whether its id is in the text file and if the code found its id in the text file "ignore.txt", then let the bot just start ignoring it
in this code:
msg_dump_channel = 886496848196542514
ignoreusers = []
@bot.event
async def on_message(message: discord.Message):
channel = bot.get_channel(msg_dump_channel)
if message.author == bot.user or message.author.id in ignoreusers:
return
if message.guild is None and not message.author.bot:
iduser = message.author.id
nameuser = message.author.name
text = message.content
embed = discord.Embed(title = "Личные сообщение бота: ", description = (f"css\n{ text }"), color = 0x1f8b4c)
embed.set_footer (text =f"ID автора: {iduser} | Ник автора: {nameuser}")
embed.timestamp = datetime.utcnow()
await channel.send(embed = embed)
await bot.process_commands(message)```
then the error has to do with type?
how do make it so that's mentioning the bot is also a prefix?
indeed
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
aight thanks
should it be like this?
await interaction.respond(type = InteractionEventType(2), embed = paginationList[current], components=[[Button(label = "⏮", id = "backk", style = ButtonStyle.blue), Button(label = "◀️", id = "back", style = ButtonStyle.blue), Button(label = "▶️", id = "front", style = ButtonStyle.blue), Button(label = "⏭", id = "frontt", style = ButtonStyle.blue), Button(label="❌", id = "exit", style=ButtonStyle.red)]])
id assume just the integer
nvm i just needed to replace interaction.respond to interaction.edit thanks for helping me out!
Hey @graceful palm!
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:
Hi, I'm trying to make a bot that can run console commands on my PC and output them as a message.
I'm able to run commands like 'taskkill' and 'ping', but if i try something like 'echo', 'cls', or 'start', I get this error:
https://paste.pythondiscord.com/soyeloxiqo.sql
Anyone know how to fix it?
Code:
@bot.command()
async def run(ctx, *, command):
if str(ctx.message.author.id) == '410281148128690198':
output = subprocess.check_output(command).decode('utf-8')
await ctx.message.reply(f'Successfully ran command: {output}')
from discord.ext import commands
from discord.utils import MyClient
#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.command()
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)
class MyBot(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
word_list = ['Hore', 'faen', 'Faen', 'hore', 'fitte', 'Fitte', 'fuck', 'Fuck']
# don't respond to ourselves
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
word_list = ['Hore', 'faen', 'Faen', 'hore', 'Fitte', 'fitte', 'fuck', 'Fuck']
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("Er ikke lov med .dll")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("Er ikke lov meg .exe")
else:
break
bot = MyBot()
bot.run('my token')``` help me pls
the !clear command doesnt work
there is no error the !clear doesnt work thats it
binds[z.reactions[ind].emoji.id] = rpl2.content gives the error: 'str' object has no attribute 'id'
But according to the reference, id is an attr of emoji??
@bot.command(aliases=["SERVERINFO", "Serverinfo", "Serverinformation", "SERVERINFORMATION", "serverinformation"])
async def serverinfo(ctx):
embed = discord.Embed(title="Server information",
colour=ctx.guild.owner.colour,
timestamp=datetime.utcnow())
embed.set_thumbnail(url=ctx.guild.icon_url)
fields = [("ID", ctx.guild.id, True),
("Owner", ctx.guild.owner, True),
("Region", ctx.guild.region, True),
("Created at", ctx.guild.created_at.strftime("%m/%d/%Y %H:%M:%S"), True),
("Members", len(ctx.guild.members), True),
("Humans", len(list(filter(lambda m: not m.bot, ctx.guild.members))), True),
("Bots", len(list(filter(lambda m: m.bot, ctx.guild.members))), True),
("Text channels", len(ctx.guild.text_channels), True),
("Voice channels", len(ctx.guild.voice_channels), True),
("Categories", len(ctx.guild.categories), True),
("Roles", len(ctx.guild.roles), True),
("\u200b", "\u200b", True)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await ctx.send(embed=embed)
is there something wrong with my code?
how do i fix this problem i cant figure out whats wrong?
File "C:\Users\okimii\Downloads\bot.py", line 18, in animeme
top = subreddit.top(limit = 5)
AttributeError: 'coroutine' object has no attribute 'top'
can i see code?
sure
import discord
import time
import asyncpraw
from discord.ext import commands
client = commands.Bot(command_prefix ="$",help_command = None)
reddit = asyncpraw.Reddit(client_id = "XXXX",
client_secret = "XXXXXX",
username = "XXXXXXXXXXX",
password = "XXXXXXXXXXX",
user_agent = "XXXXXXXXX")
bot = commands.Bot
@client.command()
async def animeme(ctx):
subreddit = reddit.subreddit("Animemes")
all_subs = []
top = subreddit.top(limit = 5)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name)
em.set_image(url = url)
await ctx.send(embed = em)
why two constructors?
snow can u help me with something`?
personally im shit at coding but i think it might be that "top" isnt defined but im probably wrong lmaooo
no.
ok
Top is from the asyncpraw library
ah mk
It gets the top submissions from the subreddit
you should use bot = commands.Bot(...) not client = commands.Bot(...), for some reason you have both? bot is better practice since discord.Client() is a thing.
ok thanks
it honestly doesnt make a difference coming from someone whos used both
just depends on what you're doing lol
or what you wanna do/use it for
from discord.ext import commands
from discord.utils import MyClient``` it's not "myclient" what is it i don't remember...
it's not dependent on what you're doing, if you're using discord.ext.commands.Bot you should always use bot as the variable, its better practice-wise so it doesnt get confused with discord.Client().
snow u talking to me or the other guy?
alr lol
how so?
also u should use bot and not client 🙂
read the link i sent
wiser can u help me with something?
What is commands.Bot even used for
it does the same thing but "bot" can do more
yeah
from discord.ext import commands
from discord.utils import MyClient``` what is it suppost to be, the "myclient" part i dont remember
discord bots? commands.Bot is far better than discord.Client(), commands.Bot has command decorators, permission check decorators, and tons more. if you're creating a discord bot, using discord.Client() isn't the go-to choice for it.
what is what supposed to be?
from discord.ext import commands
from discord.utils import MyClient
#discord.Intents.all()
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.command()
async def clear(ctx, ammount=90):
await ctx.channel.purge(limit=ammount)
class MyBot(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
word_list = ['Hore', 'faen', 'Faen', 'hore', 'fitte', 'Fitte', 'fuck', 'Fuck']
# don't respond to ourselves
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
word_list = ['Hore', 'faen', 'Faen', 'hore', 'Fitte', 'fitte', 'fuck', 'Fuck']
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("Det er ikke lov med .dll filer.")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("Det er ikke lov meg .exe filer.")
else:
break
bot = MyBot()
bot.run('mah token')``` the !clear command doesnt work, doesnt have any errors either
I just realized that I actually use commands.Bot I just named it client
i created a entire moderation bot, ticket bot, economy bot, and recreational bot with 800 lines of code in the main.py and 15 cogs with 300 lines each and used "client" and im telling you now, it does the same thing
wiser can u help me..?
yes
i sendt the code and shit
oh okay
i dont think you understand
of course the variable name wont change anything, why would it? of course it will function the same. you could name the variable literally anything and would be fine, maybe if you payed attention to my messages, you'd see that i said its better from the aspect of practice
as i said: if you're using discord.ext.commands.Bot you should always use bot as the variable, its better practice-wise so it doesnt get confused with discord.Client().
@crude crater
Didnt you say you changed it to bot
and i already said this like 5 minutes ago cutie, end of discussion it doesnt change much
yeah lmao
reddit.subreddit needs to be awaited and when you're looping through the submissions you need to use an async for loop
but i ran it with client before (as u know ;))
you spelled amount wrong
I'm building a basic bot, but when I import another file the bot doesn't run. Or if I import the bot into the other file, then that doesn't run. Anyone want to take a look at my code and point out where I'm going wrong?
1
its yellow
sure lemme see
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
import time
import discord_message
PATH = "C:\\Users\\phult\\AppData\\Local\\Programs\\Python\\Python39\\Lib\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.set_window_size(720, 440)
options = Options()
# URL and page element
product_link = "https://www.bestbuy.com/site/hamilton-beach-burr-coffee-grinder-stainless-steel/6447745.p?skuId=6447745"
def stock_check():
driver.get(product_link)
add_to_cart_button = driver.find_element_by_css_selector("div[class=fulfillment-add-to-cart-button]")
stockStatus = add_to_cart_button.text
# Loop to check status at timed interval
while True:
driver.refresh()
time.sleep(5)
if stockStatus == "Sold Out":
pass
else:
print(stockStatus)
time.sleep(10)
stock_check()
import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
bot = commands.Bot(command_prefix="!")
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
# Initial bot login
@bot.event
async def on_ready():
print("Logged in as")
print(bot.user.name)
print(f"Bot User ID: {bot.user.id}")
@bot.command()
async def stock_Status(ctx):
await ctx.channel.send("Message")
bot.run(TOKEN)```
@bot.command()
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount : int):
await ctx.channel.purge(limit=amount)
await ctx.send(f'Message Clearing Complete!')
In either direction if I import one to the other, the main file stops running
@slate swan
where do i put the amount? do u just write it?
yes
Sorry, I'm still pretty new so sorry if I get any terminology wrong
you could use an f-string in your on_ready rather than 3 print satements, and ctx.send() is the same as ctx.channel.send(), so you dont need channel.
doesnt work
whats the error?
Yeah I know for sure there are places I can clean it up
i dont know then because it should work lol
weird
are your commands even being executed? you may have an on_message event and arent processing commands
@slate swan
in your on message event, add await bot.process_commands(message)
or client if you are using client
fixed it i think
alright
👍
any thoughts on my issue?
Whats the issue?
I pasted my code above, I'll drop it in again
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
import time
import discord_message
PATH = "C:\\Users\\phult\\AppData\\Local\\Programs\\Python\\Python39\\Lib\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.set_window_size(720, 440)
options = Options()
# URL and page element
product_link = "https://www.bestbuy.com/site/hamilton-beach-burr-coffee-grinder-stainless-steel/6447745.p?skuId=6447745"
def stock_check():
driver.get(product_link)
add_to_cart_button = driver.find_element_by_css_selector("div[class=fulfillment-add-to-cart-button]")
stockStatus = add_to_cart_button.text
# Loop to check status at timed interval
while True:
driver.refresh()
time.sleep(5)
if stockStatus == "Sold Out":
pass
else:
print(stockStatus)
time.sleep(10)
stock_check()
import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
bot = commands.Bot(command_prefix="!")
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
# Initial bot login
@bot.event
async def on_ready():
print("Logged in as")
print(bot.user.name)
print(f"Bot User ID: {bot.user.id}")
@bot.command()
async def stock_Status(ctx):
await ctx.channel.send("Message")
bot.run(TOKEN)
If I import the statuscheck file into the bot file, the bot doesn't run
If I try it the other way, then the statuscheck doesn't run and the bot does
Sorry, the two run fine independently of each other