#discord-bots
1 messages Β· Page 587 of 1
Repo means a repository
what does that mean? backup?
π
a central location in which data is stored and managed. i googled this
https://github.com/DisnakeDev/disnake is a repository
advertising
so i copy paste my code in here?
ban!!
/j
Ok
Do*
Can I get some help?
stolen message
.topic
Suggest more topics here!
Not force slash commands:/
!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").
hey how in the world do you change a bot's presence status
here's my sample code of a bot.event on_ready thing:
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
await bot.change_presence(game=discord.Game(name='!help'))
print("Bot ready")```
this is my error
TypeError: change_presence() got an unexpected keyword argument 'game'
!d discord.Game
its bot.change_presence(activity=discord.ActivityType.playing(name="!help")) i think
What is the best library as for now? ;)
thats what i thougth
im back
typo π€£
got another error π
TypeError: '_EnumValue_ActivityType' object is not callable
;-;
try adding status=discord.Status.online
how do i make a git repo
as in like bot.change_presence(status=discord.Status.online, activity=discord.ActivityType.playing(name="!help"))
oh wait no
i dont really have an existing presence except this one im making rn
are u doing this for the 247?
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.playing, name=f"!help"))
thats what it is
lmao
lmfao
oof
for u its bot.change_presence
you couldnt google this?
137 characters of code only to summon a presence in your discord bot, speechless...
lol
idk why i need to do this
imma just skip this step
π
:)
what are you doing?
ye th ecode works thanks for hlrping killby
changing from replit to heroku
n op rob lem
eh why switch
they say replit db noob
it is
idk
so why are you changing then
they say there is
ah ok then
how do i create a vc channel in a certain category with certain member limit and permissions
i trust them π€£
in discord with bot?
or what
just do it with hand >:)
lol
ig I'll google lol
true
stackoverflow
-> step 3: go to settings and add python buildpack, then click "Reveal Config Vars" and add your bot token, along with whatever you have in your .env there
where is the python buildpack
alright i found it
Iirc they give 1GB of postgresql
For their free plan
Because heroku is infinitely better than shitplit
Sheesh that's my quick tutorial on how to set it up π³
where do i edit codes
ya i found that from u
Feeling useful π
:)
Use an editor
=.=
When ur done upload the code to github, then heroku will automatically pull the latest changes
??
#help-pretzel π₯Ί
i googled couldnt find
just tell me how to create inside a category
and member limit
idk
\\\\\\
π€§ π³
create file
ig
what does this mean
-> step 5: make sure your bot directory has a file named Procfile which has "worker: python main.py" (or whatever the file that runs your bot is) and a requirements.txt where you have your requirements listed in newlines
https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.create_voice_channel
the docs has everything you need
I absolutely did not link it to them
Exactly what it means?
where to create
@slate swan u use heroku right π€¨
here?
In the root, where your main file is
Yes
π€§
what root =.=
Yes
where ur main file is
what do i press
is there something like client.get_category() ?
add file?
create file
Click Add file
Can you use postgres in between 2 accounts?
And go look at some yt tutorials about it please
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
category not channel
Not sure, never used it, just heard it's a thing
categories are channels..
i type worker: python main.py in there?
oh ?
It's get_channel, it returns a category too
yes
Name Procfile, file content is worker: python main.py
Is there a list of Discord.Color.***()
like this?
are you sure if i do client.get_channel() and enter id of a category it will work since category and channels are clearly different
or here
source code or dir(discord.Color)
there i tons of channel in a category
click save
i wanna find category not channel
yes
alright ty imma try
Im certain
where can i do "dir(discord.Color)"
it will return a list of all the methods the class has, print it where ever you want
a
oh in python you meant, alright thanks
ignore the ones starting with _
alright :)
dunder methods
second one
ok
first one is for giving details about commits
"@commands.Cog.listener()" <- what's cog on this command line (im studying still)
oo
Can I have some help with mute channel permission changes? This current line does nothing
it's like a event listener
await ctx.channel.set_permissions(target=ctx.guild.default_role, send_messages=False)
!d discord.ext.commands.Cog read this
a requirements.txt where you have your requirements listed in newlines
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
whats requirements.txt
but its like a command?
u dont need target kwarg afaik
@dusk dust
how do ping role with role id
<@&id>
isit ok if i use heroku even i dun open my laptop often
where id is role id?
ofc
developer mode
ig
a requirements.txt where you have your requirements listed in newlines
Still doesn't work
whats this
show code
a requirements file
how
how?
like how i create the other one?
yes
yes
error
when u hit enter it will change
must be a string
just create it
he did that but it wasnt in a string
right sorry
what do i write inside
@boreal ravine
idk google but smth like this
discord.py==2.0
That will error
@mortal dove errors?
i said google smh
None
this?
Every newline needs to be a dependency/package, how it works is it takes every line and does pip install on it
No
then what do i write
Something like that yeah, but not that
Your dependencies/packages
import?
Bruh
isn't it great that you get again to go through this?
=.=
Nope I'm not helping, not gonna waste my time getting mad at it again πΆββοΈ
;-;
idk what to do
Was I that bad π
lets say you have two modules, x and y are their names. so your file would look something like this:
x
y```
i dun understand
os
random
discord
is this what i write
not built-in ones
Not really but rn I feel like I'm talking to a toddler that doesn't know how anything works
external libs
import discord
import discord.ext.commands
import os
import random
i only have these in my code
oh that sucks, have a break and focus on something completely else
I don't generally help anyone who's new to coding at all anyways, it's just a big waste of my time and nerves
put omly discord there
ok
im just changing my codes from replit to heroku :(
Β―\_(γ)_/Β―
no Procfile
how do i reload the thing
so the new files will be detected
its a nightmare ;-; @maiden fable
Go to deploy -> Enable automatic Deploys (scroll down the page)
alright
Sorry dude, I can't really help anyone rn since I am getting a headache whenever I am seeing something in light mode ;-;
oof
good excuse
light mode is very bad
π€§
change it to dark mode then >:)
Nahhh, it happens when I am unwell and this is the case rn
you got it?
Refresh the page
i refreshed it
After enabling automatic deploys make sure you also click the deploy button
ok
Scroll a bit down and click deploy
sounds like situation I had
π π₯ π« ποΈ
.
yes
its there
how do i start the bot with heroku
deploy = start?
but heroku looks weird
replit is better =.=
!pypi discord-ext-ipc
A discord.py extension for inter-process communication.
then use the button to activate it
Yeah heroku is kinda weird
.
!d discord.ext.commands.group
!d discord.ext.commands.Group <=
class discord.ext.commands.Group(*args, **kwargs)```
A class that implements a grouping protocol for commands to be executed as subcommands.
This class is a subclass of [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and thus all options valid in [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") are valid in here as well.
anyone familiar with discord.ext.commands.HelpCommand ?
yes
in what situations would HTTPException be raised for try excepts?
how do i unfilter a cog, part of my code:
for cog, commands in mapping.items():
if filtered_commands := await self.filter_commands(commands):
amt_cmds = len(filtered_commands)
usable += amt_cmds
if cog:
name = cog.qualified_name
description = cog.description or "No description"
else:
pass
unfilter?
yeah like show it on the actual help
set the help command to that?
now it doesnt show that cog to whoever that doesnt have perms
example:
im the owner/mod of server, so i can see the mod commands...
but regular users, cant see that cog
!d discord.errors.HTTPException
exception discord.HTTPException(response, message)```
Exception thatβs raised when an HTTP request operation fails.
btw cringe ternary operator β οΈ
well
check your code maybe u did smth wrong
idk what it does π
why u using it then?
i'll send the whole one, irdk what i did wrong
π€¨ ..
it works
async def send_bot_help(self, mapping):
ctx = self.context
em = discord.Embed(
title=f"{ctx.me.display_name} Help Menu",
timestamp=ctx.message.created_at,
color=bot.color
)
em.set_thumbnail(url=ctx.me.avatar_url)
usable = 0
for cog, commands in mapping.items():
if filtered_commands := await self.filter_commands(commands):
amt_cmds = len(filtered_commands)
usable += amt_cmds
if cog:
name = cog.qualified_name
description = cog.description or "No description"
else:
pass
em.add_field(name=f"{name} [{amt_cmds}]", value=description, inline=False)
em.description = f"""{len(ctx.bot.commands)} commands | {usable} usable\n\nUse "help [command | module]" for more info\n`<>` required | `[]` optional"""
await self.send(embed=em)
well I dont know whats wrong
me too
Β―_(γ)_/Β―
it should show those cogs normally?
yes ig
my friend also uses HelpCommand but he hard-coded those cogs
he typed out all the names of the cog.. im doing like this bcz i dont want to update it everytime when i make a new cog
thats bad
yeah
hii,i was tryin to make buttons for discordbot but i saw that Interaction type is removed from discord component, so what can i do to make buttons?
can anyone help
!pypi dislash.py is a great 3rd party library.
oh thanks
what code do i write to get id from user
if message.content.startswith('rpm hunt'):
await show_hunt(message)
can someone add it in here?
message.author.id
!d discord.Message.author use id attr
if message.content.startswith('rpm hunt'):
await show_hunt(message)
userid = message.author.id
yes
isit like this?
yes
where do i write that
where you want
hi
hi

π₯ π« 
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Read.
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
will it work if i write like this
is ramnode a good vps?
maybe
why wouldn't it
You used bot before defining it.
he prolly had it?
wdym
It will not work, he defined bot at the end.
oh
i define bot at the last line of code
didnt see;
do you know what variables are and how to use them π€¨
!e
print(name)
name = "Seif Wessam"
@dapper cobalt :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'name' is not defined
how to convert datetime obj to str?
newdatetime = str(datetime)
i guess
str function
hi im using ms vs code
and its says that there is not module named discord
but i tried pip install discord
and it says requirement already satisfied
show the pyflake
yup there u go
Click ctrl + p
press >
search python linter or smth
and click that
click the other python thigny
hit >
show full ss
ok
You have multiple python interpretet
^
Type python intreprer
And select your python
select linter
Linter is different
Linter is flake8
ah
yup done
yeah @ornate lichen search interpreter or smth
i select 3.1.10
hm
but i need one that is supported by heroku
Don't host bots at heroku
heroku doesnt support 3.8.9?
I think it does
I recommend to focus on completing bot first then worry for its homeπ
it was working in the afternoon
Make new app
probably because i downloaded the 3.10 thingy python
It's restoring data from cache
No unless u have friend who gives u hosting or host it for u
I recommend to not use heroku
Yeh it will work
1 year free i think
Yep
call the function
def get_mean():
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"wat"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': ""
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data=json.loads(response.text)
mean=json_data
return(response.text)
just use error param
Use aiohttp
Request will block your code
it doesnt take arguments y u using hello
@client.command()
async def define(ctx,term):
mean=get_mean
await ctx.send(mean)```
call the function
Yes
wdym
!e
def a():
print("b")
a()
i m getting a rsponse from an API in [{},{}] form
@mild token :white_check_mark: Your eval job has completed with return code 0.
b
how can I parse that into a list ?
Index it
i still dont get it lol
which means/.
do i print the data?
you call functions by ()
isnt it already a list
@client.command()
async def define(ctx,term):
mean=get_mean
await ctx.send(mean)```
you dont need to post your code multiple times
Check get _mean line use get_mean()
I do request.get and I get it as a string
Learn python then, that's a really beginner thing, you clearly straight up jumped to a discord bot with no knowledge of coding at all π€¨
I do response.content
well, it is but
!e
print(type([{}]))
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
<class 'list'>
already a list
yo
yo
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
pls help me
your using on_command_error right?
I think he is trying to access data inside the list and then make it list
ohhh
!e Pythorn
@ebon plank :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'Pythorn' is not defined
well on_command_error takes 2 parameters (ctx, error) use error to get the missing permission idk if it works with missing perms though
sure I guess
Simple Error Handling for ext.commands - discord.py - error_handler.py
indexing => list function
I know buddyπ
ret = await coro(*args, **kwargs)
File "/Users/aarav/Documents/GitHub/awaffle_bot/main.py", line 139, in define
await ctx.send(mean)
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 4000 or fewer in length.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 4000 or fewer in length.```
im getting this noe
now
lol
try awaiting the json
anyone help me?
post your code and error
I don't think it's a problem
He is sending more than 4000 char
let me show
well
yup it isnt working
i am a newbie who don't know pythorn
response.text sends the website content iirc
Sorry wrong tagπ
but it shows like this
shld i try to priny in terminak
I guess
Shows what
Then i recommend to learn atleast basics mate after that jumping into coding discord botsπ
you could do
data = response.json()
``` and then sending `data` will return the json output
Hey @ornate lichen!
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:
@ornate lichen this
yup i printed the data
request will block his code right ,discord.py is async wrapper
well
it isnt an async function innit?
really depends on him though
Ahh fair
{"list":[{"definition":"The only [proper] [response] to something that makes absolutely [no sense].","permalink":"http://wat.urbanup.com/3322419","thumbs_up":3874,"sound_urls":["http://wav.urbandictionary.com/wat-25563.wav","http://wav.urbandictionary.com/wat-25758.wav","http://wav.urbandictionary.com/wat-32201.wav"],"author":"watwat","word":"wat","defid":3322419,"current_vote":"","written_on":"2008-09-04T02:15:08.000Z","example":"1: If all the animals on the [equator] were capable of [flattery], Halloween and Easter would fall on the same day.\r\n2: wat\r\n\r\n1: Wow your cock is almost as big as my dad's.\r\n2: wat\r\n\r\n1: I accidentially a whole [coke bottle]\r\n2: You accidentially what?\r\n1: A whole coke bottle\r\n2: wat","thumbs_down":439},{"definition":"Slang. Indicates [confusion] or a need for [clarification]. [Statement]/question.","permalink":"http://wat.urbanup.com/1308686","thumbs_up":1206,"sound_urls":["http://wav.urbandictionary.com/wat-25563.wav","http://wav.urbandictionary.com/wat-25758.wav","http://wav.urbandictionary.com/wat-32201.wav"],"author":"stewpidwhytemayun","word":"wat","defid":1308686,"current_vote":"","written_on":"2005-06-08T16:20:56.000Z","example":"1: \"[lolz] Yea sex is great and everything
this is some
the repsonse.content is giving it to me in b' form
Why requests
That's the response you got from the API you're making the request to
Now you just have to index in some lists and some dicts
?
index*
trivia=str(json_data["number"] )+ " -" + json_data["text"]
like this
this is another func
why use another func
what ya need @boreal ravine
just index the data
help π
every api response is funny
its urban dictioary
No read its content
with what
i asked do define hello
i can read
It's content is funny i mean
helping people π
busy rn lol
any documentation on howto index data?
yes so what do you still need
!resources yes
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
hi i have created a music bot but when i type the "join" command i'm getting this error in my console
Ignoring exception in command None:
Why not just index it normally
My net is slow i sent before u
discord.ext.commands.errors.CommandNotFound: Command "join" is not found and this too
show code
But it sended my message after u
import discord
from discord.ext import commands
import DiscordUtils
client = commands.Bot(command_prefix='.', intents = discord.Intents.all())
Music = DiscordUtils.Music()
@client.event
async def on_ready():
print('ready')
@client.command
async def join(ctx):
await ctx.author.voice.channel.connect()
await ctx.send('joined')
@client.command
async def leave(ctx):
await ctx.voice_client.discord.disconnect()
await ctx.send('successfully left the vc')
!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)
thr are only 2 fours
DiscordUtils uses youtube_dl
so why is the output 3
I am sure they have documented it well
If u read on same website
3,0 bcz both have cat word
Index start from 0
No.
Then?
oh ok
The 3 is for the print above, the 0 is for the print below
Bruh@slate swan
It only outputs the first index found, never all
So not "3,0 because both have cat word"
LOL
!e
l= ['a','b','a']
print(l.index('a'))
@mild token :white_check_mark: Your eval job has completed with return code 0.
0
timestamp in embed?
Β―_(γ)_/Β―
u pass it in the objec arguments//.?
!e
l = ["a", "b", "c"]
print(l[2])
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
c
easier
It's not the same
saves 5 words π±
its different
i know, you can index it using strings to find certain values i guess
Yours prints the value at index, the example above prints at which index the value is
So you end up doing more if you use what you've given
hm
wait so
t=Translator()
a=t.translate(args,dest=lang)
await ctx.send(a.text)```
i do smth like this
this is the translating func
whats do here
mean=str(json_data["word"] )+ " -" + json_data["definition"]
like this?
For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.
i guess
why not f"{json_data['word']} {json_data['definition']}" though
i dont understand that
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
its not working lol
Traceback (most recent call last):
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/aarav/Documents/GitHub/awaffle_bot/main.py", line 139, in define
mean=get_mean()
File "/Users/aarav/Documents/GitHub/awaffle_bot/main.py", line 79, in get_mean
mean=str(json_data["definition"])
KeyError: 'definition'
definition doesnt exist
i checked tho
I need help
sure
I have this here
isnt definition right after that?
2021-11-08 14:19:03.801979
yes
How do I add it in the footer, timestamp
so why doesnt it exist
I ve done that, but I get just the date not the time too
well learn more about indexing cant explain rn
datetime_object = datetime.strptime(data["last_updated"], '%Y-%d-%m %H:%M:%S.%f')
oh ok
!d discord.Embed.timestamp
The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.
so what do
#βο½how-to-get-help for other help, this is for Discord bots.
yes ik, but the time isnt passing thru
I just get the date
i have a stupid in my brain
use global
what
How to remove an element from an array by index in mongodb with python?
why global 
!global
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
nice job 
someone help me (:
Where is the element?
it is stored in mongodb databse
the databse contains elements from there i had to remove a specific index of the array element
I only use SQL based syntax so i recommend going to #databases
its discord bort
oh ok thx
@bot.command(name='unban')
@commands.has_any_role("πππππ π","π§βDeveloper-dc","πππΏ","πΌππ’ππ£")
async def unban(ctx, *, member: discord.Member):
bans = await ctx.guild.bans()
member_name, member_id = member.split('#')
for ban_entry in bans:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_id):
await ctx.guild.unban(user)
await ctx.send(f"Gracz {user} ZostaΕ odbanowany przez {ctx.author.name}.")
``` its code
and i have error dont found user
member.id and member.name exists lol
help this dude if u can
I really can't since the error basically tells him to define that variable.
he has no brain (like he said)\
just define empty countminers variable. eg:countminers=""
Hey everyone, I am making a public discord bot and my bot is in some servers im not in so is there a way to figure out what servers my bot is in?
just like you said
bot.guilds
so what do?
Paste the errors
This seems kinda inappropriate, why?
ok, wait
it is within if loop. I guess it will be rectified by defining global or just creating variable before if
It isn't inappropriate.. sorry if it seems like it
more info about it: it is item checking (it checks for amount)
what if i just
haha
They may be private servers not meant to join, if you could ask staff here if they allow it i will help, otherwise no.
oof then globaling is the way π
huh i never thought of that.. I'll ask the staff brb
do i ping a staff member?
You can just ask modmail, send this link too for reference -> #discord-bots message
π
Why would you unban someone by name and discrim anyway? Seems like a security flaw
i want unban using id
So I made (or tried making) a simple Management bot.
Decided to implement a "warning" system.
Got it somewhat working, but when I check my own history with the command,
all the previous warns of other people show up and if I check their history,
it shows up as they don't have warns, even though they're clearly listed there
and picked up by the warn command
Here are some pictures of what I mean and some of the code:
async def warnings(ctx, Member : discord.Member): if Member is None: return await ctx.send("Please provide a user.") else: with open('warns.txt', 'r') as f: warns = f.read() if str(Member) in warns: await ctx.send(f"Showing warns for {Member.mention} || {warns} ") else: await ctx.send("This user has no warnings.")
I'm not even sure you can put role strings in like this.
i think i managed to fix
relatively new to this type of this, sorry if the code is horiffic
lemme test
i did omg omgomgomgogmgogmogm
File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "C:\Python39\lib\site-packages\discord\ext\commands\core.py", line 451, in _actual_conversion
ret = await instance.convert(ctx, argument)
File "C:\Python39\lib\site-packages\discord\ext\commands\converter.py", line 195, in convert
raise MemberNotFound(argument)
discord.ext.commands.errors.MemberNotFound: Member "787073733801410560" not found.
ctx.guild.unban(discord.Object(idhere))
but i want use this command using .unban id player
User that you pinged was not found.
i use id
Staff didn't respond to me yet but when you invite my public discord bot it says "Create Server Invite" in the permissions.. That notifies them
i want bot unban using id
I recommend a converter then.
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
add this?
As typehint yes.
Original 
?
I donβt even know what you want anymore tbh. Youβre saying you want to unban by Iβd right? What I said checks out.
π
Good luck mate
have them pass in an id as command argument.
Could you tell me what a type hint is?
Just put this in a try/except
This is pretty bad advice.
im lost
discord.Object is not meant to convert.
And except a HTTPException and assume if thatβs raised that user is invalid.
what to do, i got lost
I mean Iβm not telling him to convert anything
Hi
Iβm just telling him Iβd he wants to unban by id. Than what I said in the most minimalist way to do it.
I'm looking for some discord Devs who can work with me ;_;
I'm doing a lil startup
I want Devs (no money but)
This whole unban command is wrong i mean he is iterating over the ban list instead of looking in it.
Whatβs the point in iterating over the ban list
w-what do
Anyone interested pls contact me
Heβs only doing that to match the username and discrim.
Bye have a good day
@sage otter add this? ctx.guild.unban(discord.Object(idhere))
This channel is not meant to look for devs.
Where then
If you want to only unban by id. Which I recommend.
I need some good guys
Then remove all that garbage thatβs there and put that in. So yeah.
just use discord.User
i want it
π€§ π€§
@bot.command(name='unban')
@commands.has_any_role("πππππ :crown:",":wrench:βDeveloper-dc","πππΏ","πΌππ’ππ£")
async def unban(ctx, *, member: discord.Member):
bans = await ctx.guild.bans()
member_name, member_id = member.split('#')
for ban_entry in bans:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_id):
await ctx.guild.unban(discord.Object(idhere))
await ctx.send(f"Gracz {user} ZostaΕ odbanowany przez {ctx.author.name}.")
remove bans = await ctx.guild.bans()
member_name, member_id = member.split('#')
for ban_entry in bans:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_id):
?
Hello! Im running a bot with heroku. But gets certificate ver ify failed: unable to get local issuer certificate
how can i solve this?
Thereβs no point in converting the argument if itβs consistently gonna be a int anyway
typehint member to int
And try except the unban
imo its better
@sage otter what do? change user to member?
.
Typehint the member argument to int
what? int?
MemberConverter even better it's literally made for the job :(
isnt that automatic
No?
where give member
like if u use discord.Member and pass in an id as the arg it'll find the correct converter to use
yes
And thats working?
whatβs the point of converting itβs just more work for the bot to do. If you have the id. Just unban it. Thereβs no need to convert
If the Guild.unban() raises an HTTPException just assume that id is invalid.
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'defin
mean=json_data["definition"]
i did this
!resources learn how to index stuff properly
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Yes i agree but idk with discord.User
And tbf with MemberConverter you look smarter
π
why
there you can code bots
@sage otter
and sometimes doesnt print the error
do you any other site where we can code bots with pythorn?
YES
any ide i thought
so i can work on that
Hey everyone, how do i restrict a command to a role
Remove member: discord.Member. And try and except it like I said.
and i am planning on a pythron bissness
already
but i am a newbie to pythorn
ngl i used to use it always in august β οΈ
Will this even resolve correctly if there not in the guild.
nope
Hey, is there a way i can restrict a command permission to a role?
"All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache."
Ignoring exception in command define:
Traceback (most recent call last):
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/aarav/Documents/GitHub/awaffle_bot/main.py", line 141, in define
mean=get_mean()
File "/Users/aarav/Documents/GitHub/awaffle_bot/main.py", line 81, in get_mean
mean=json_data[list][0]["definition"]
KeyError: <class 'list'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/aarav/Library/Python/3.8/lib/python/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: <class 'list'>
@sage otter now?
Try and except it
@bot.command(name='unban')
@commands.has_any_role("πππππ π","π§βDeveloper-dc","πππΏ","πΌππ’ππ£")
async def unban(ctx, *, arg: int):
await ctx.guild.unban(discord.Object(idhere))
await ctx.send(f"Gracz {user} ZostaΕ odbanowany przez {ctx.author.name}.")
``` how?
So no then? Because the member youβre trying to unban wonβt be in the guilds cache if theyβre not in it? Right?
Dude I canβt help you with simple python bro
well he isnt english he might not understand
im from poland
try:
unban method
except HTTPException:
tell them itβs an invalid id
Well true but when unbanning you need a Member right? How else would it know where to unban the user? You can also Union this discord.ext.commands.UserConverter
How so?
because you donβt need the member object
.
{"list":[{"definition":"The only [proper] [response] to something that makes absolutely [no sense].","permalink":"http://wat.urbanup.com/3322419","thumbs_up":3874,"sound_urls":["http://wav.urbandictionary.com/wat-25563.wav","http://wav.urbandictionary.com/wat-25758.wav","http://wav.urbandictionary.com/wat-32201.wav"],"author":"watwat","word":"wat","defid":3322419,"current_vote":"","written_on":"2008-09-04T02:15:08.000Z","example":"1: If all the animals on the [equator] were capable of [flattery], Halloween and Easter would fall on the same day.\r\n2: wat\r\n\r\n1: Wow your cock is almost as big as my dad's.\r\n2: wat\r\n\r\n1: I accidentially a whole [coke bottle]\r\n2: You accidentially what?\r\n1: A whole coke bottle\r\n2: wat","thumbs_down":439},{"definition":"Slang. Indicates [confusion] or a need for [clarification]. [Statement]/question.","permalink":"http://wat.urbanup.com/1308686","thumbs_u
The only proper response to something that makes absolutely no sense.
The only proper response to something that makes absolutely no sense.
why am is till getting all this
this is my code
arg change to var?
can embed title icon_url take links ?
yes
icon_url="https://cdn.discordapp.com/attachments/826871393617969233/907286488469893140/1636384320707.png" this should work right?
weird
yes
but isnt working
Now Thats A Big Code
hm
@sage otter
I meant the user var
help pls
i indexed it like this
but im stillgrtting all that
beacause u talk it
no I didnβt bruh
except discord.HTTPException
@sage otter already
replace idhere with arg
okey
remove the * from the command its useless
isnt the discord.py lib no longer supported?
stopped devlopment*
replace var with arg.name
hey anyone help me as guide? so i can code a bot in a site and btw pls say a site where i code pls @boreal ravine i think you can help me out?
print something at except to know that the id isnt a user
like "user does not exist" or something
discord.py or disco.py lib?
IDEs
disco.py is so old and I mean discord.py
but discord.py is no longer in use after december?
@boreal ravine good?
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.
yes
thx @boreal ravine
well people still use it
it isnt banned or anything
whats next?
nothing, the command is done :)
i thought it will be unusable after december... lol
can you send a video?
π€¨ google
thank u very much β€οΈ
wrong reply π
maybe?
i dont want to get banned what which discord bot API would u recommend? For complicated stuff
@boreal ravine :/

πΏ
its lines
can i use discord.py for that?
is this video ok @boreal ravine? https://youtu.be/T5moR5gBlbM
In this video, we will create a Discord Bot with discord.py v1.7.3 in 2021. This is an updated version of the video where I showed how to do the same thing last year.
If you have any suggestions for future videos/doubts, leave it in the comments below. I might not be able to answer everyone but you can join my discord server for help: https://d...
discord.py fork, you wont get banned by using an api though except if its illegal
ig means?
@boreal ravine what can i do?
i guess
no i meant which discord api (could be java or sth else) for complicated bots
k
more then basic commands etc
javascript?
djs*
doesnt matter which language
but it should be able to performe complicated bot commands/events
put this inside ur code {discord.Object(arg).name}
where?
!pypi discord.js ig
replace arg.name with the code I gave earlier
okay
i wanna do a complicated bot which will be a big project (im thinking of 1 or 2 thousend lines of code(or more))
hey can anyone say how to install discord.py?
which API should i use for that?
pip install discord.py
- it isnt an api
- just use a lib ur comfortable with
which lib for the discord api
`def get_mean():
url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"
querystring = {"term":"wat"}
headers = {
'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com",
'x-rapidapi-key': "---"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data= json.loads(response.text)
mean=json_data["list"][0]["definition"]
return(mean)`
can we have personal VC?
which lib would u recommend
im on mobile
-/?
take parameters
@boreal ravine working but dont send embed
?
