i want to know if i can do response["rap"] == "null" then response["rap"] == "account is private"
im new to python / json reason for bad sytax an example of the api with response null is
https://i.stack.imgur.com/IWXys.png
i included full code so you can test it out and play about with the code to see if you can get it to work
thanks for reading this
async def on_me
global rap
global response1234
response1234 = requests.get(f'http://api.chloe.to/rbx?method=username&user={id}').json()
rap = response["rap"]
await asyncio.sleep(60)
if rap == response["null"]:
rap = "Private Account"
#bot.command()
async def account(ctx, id):
response2 = response1234["id"]
id2r = discord.Embed()
id2r.set_author(name='Status : Online', icon_url='https://cdn2.iconfinder.com/data/icons/greenline/512/check-512.png')
id2r.set_thumbnail (url=response1234["avatar"])
id2r.add_field(name='***Username ***', value=response1234["username"],inline = False)
id2r.add_field(name='***RAP ***', value=f"{rap}",inline = False)
id2r.add_field(name='***Rolimons Link***', value=f"https://www.rolimons.com/player/{response2}",inline = False)
id2r.timestamp = datetime.now()
await ctx.send(embed=id2r)
#account.error
async def kick_error(ctx, error):
if isinstance(error, commands.UserInputError):
support = discord.Embed()
support.set_author(name='Status : Online', icon_url='https://cdn2.iconfinder.com/data/icons/greenline/512/check-512.png')
support.set_thumbnail (url='https://i.gifer.com/VG4s.gif')
support.add_field(
name='***Error***', value='Did Not Provide Roblox Username', inline=False)
support.timestamp = datetime.now()
await ctx.send(embed=support)```
Related
So im making this Discord bot and one of the commands is to add api names and what comes with the api and so that command works and the code looks like this:
#Add a Method to the json string command
#bot.command()
#commands.has_role('Reseller')
async def addmethod(ctx,api, method):
methods = await get_method_data()
methods[str(api)] = {}
methods[str(api)]['Method'] = method
methods[str(api)]['api'] = api
with open("methods.json", "w") as output:
json.dump(methods,output)
await ctx.channel.purge(limit=1)
embed = discord.Embed(title=f'{method} has been added to list', color=0x000000)
await ctx.send(embed=embed)
Then im making another command where it grabs all the data from the json file and prints it into the Discord chat but its not making the data that i inputted print into the Discord chat here is the code of the ERROR
#bot.command()
async def methodss(ctx):
methods = await get_method_data()
method = methods['Method']
apiname = methods['api']
em = discord.Embed(title = "B")
em.add_field(name = "Wallet Balance", value = method)
em.add_field(name = "Bank balance", value = apiname)
await ctx.send(embed = em)
Where did I go wrong??
I am currently working on something that deletes a users channel when they leave, this was working fine in my test server however now i've put it on the main server it is not functioning. The error I get is shown below: ( I am using diskord.py which is 99% identical to discord.py , only difference being wherever discord should be it says diskord)
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/diskord/client.py", line 428, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/shopside.py", line 157, in on_member_remove
await channeldelete.delete()
AttributeError: 'NoneType' object has no attribute 'delete'
The intended result is it deletes the channel and the log of it in the database
The actual result is neither of these happen and in the logs shown below it says NO to the user having had a channel.
My code:
#commands.Cog.listener()
async def on_member_remove(self, member):
channelfind = cluster["Channels"]["shopside"]
if member.guild.id == shopsideid:
joinedat = diskord.utils.utcnow() - member.joined_at
time = humanize.precisedelta(joinedat, format="%0.0f")
embed = diskord.Embed(title="\u200b", color=0xfc8eac)
embed: Embed = diskord.Embed(
description= f'**{member.mention} left the server**\n:timer: **Joined:**\n{time} ago\n:question:**Shop Channel?**\n`NO`',
color=0xfc8eac
)
embed.set_author(name=member, icon_url=member.avatar.url)
embed.set_thumbnail(url=member.avatar.url)
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text=f'ID: {member.id} \u200b ')
memberid = channelfind.find_one({"member_id": member.id})
if memberid is not None:
channelid = memberid['channel_id']
channeldelete = member.guild.get_channel(channelid)
await channeldelete.delete()
deletedata = { "member_id": member.id }
x = channelfind.delete_many(deletedata)
print(x.deleted_count, " documents deleted.")
aembed = diskord.Embed(title="\u200b", color=0xfc8eac)
aembed: Embed = diskord.Embed(
description= f'**{member.mention} left the server**\n:timer: **Joined:**\n{time} ago\n:question: **Shop Channel?**\n`YES.` Channel Name was: {channeldelete.name}',
color=0xfc8eac
)
aembed.set_author(name=member, icon_url=member.avatar.url)
aembed.set_thumbnail(url=member.avatar.url)
aembed.timestamp = datetime.datetime.utcnow()
aembed.set_footer(text=f'ID: {member.id} \u200b ')
log = shopsidelog
await self.bot.get_channel(log).send(embed=aembed)
else:
log = shopsidelog
await self.bot.get_channel(log).send(embed=embed)
pass
Part of the code that the error also refers to:
#diskord.application.slash_command(description="Creates a shop channel", guild_ids=[shopsideid])
#diskord.application.option("member", description="Who is this channel for")
#diskord.application.option("name", description="Channel Name")
#diskord.application.option("category", description="Use the category ID that you want the channel in")
#diskord.application.option("description", description="If no channel description wanted type None")
#diskord.application.option("nsfw", description="True or False")
#commands.has_permissions(manage_messages=True)
async def createchannel(self, ctx, member: diskord.Member, name: str = None, category: diskord.CategoryChannel = None, description: str = None, nsfw: bool = False):
if description == None:
description = " "
category = category
memberrole = ctx.guild.get_role(shopsidemember)
moderator = ctx.guild.get_role(shopsidemod)
channel = await ctx.guild.create_text_channel(name, category=category, )
await channel.set_permissions(ctx.guild.default_role, view_channel=False)
await channel.set_permissions(moderator, view_channel=True, send_messages=True, manage_messages=True)
# SET MOD AND ADMIN ROLE PERMS HERE
await channel.set_permissions(memberrole, view_channel=True, send_messages=True)
await channel.edit(topic=description)
if nsfw == True:
await channel.edit(nsfw=True)
channelid = channel.id
await ctx.send(f"Channel Created: <#{channelid}>")
await channel.send(f"<#{member.id}> Welcome to your channel")
channeldb = cluster["Channels"]["shopside"]
newchannel = {"member_id": member.id, "channel_id": channel.id}
channeldb.insert_one(newchannel)
Any help is appreciated thank you in advance
I have been looking for help with this for a solid week now and tried a lot of things, but a lot of answers are outdated with the new Components update for discord.py
I referenced this video for this particular code: https://www.youtube.com/watch?v=1Ntw43Sg35k
This is in a cog if that matters. It worked ONCE but I didn't realize it and messed up the code so I lost it...
It pulls up the embed and even the buttons, but it does not assign the role and the component comes up with "This interaction failed".
enter image description here
Any help would be super appreciated!!
import os, json, asyncio, discord, discord.utils
from discord import Embed, Color
from discord.ext import commands
from discord_components import Button, ButtonStyle, Select, SelectOption, ComponentsBot, component
from discord_components.client import DiscordComponents
from discord_components.interaction import Interaction
from discord.utils import get
#----- Import -----#
client = discord.Client()
def get_prefix(client, message):
with open('prefixes.json','r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
client = commands.Bot(command_prefix = get_prefix,intents=discord.Intents.all(),case_sensitive=True,buttons = DiscordComponents(client))
#----- Class Code for f1r4 -----#
class f1r4(commands.Cog):
def __init__(self,client):
self.client = client
#client.command()
async def f1r4(self,ctx):
embed=discord.Embed(
title='Floor 1, Room 4',
url = '',
description = 'You decide that it\'s time to move on. Maybe, somewhere safer too...',
color=Color.green())
embed.set_thumbnail(url='')
embed.add_field(
name = 'North',
value = 'Insert an informative text dump here.',
inline = True)
embed.add_field(
name = 'South',
value = 'take two boogaloo',
inline = True)
embed.add_field(
name = 'East',
value = 'Boy howdy don\'t look at the actual descriptions lol',
inline = True)
msg = await ctx.send(embed=embed,
components=[[
Button(label = 'North'),
Button(label = 'South'),
Button(label = 'East')]])
def check(res):
return ctx.author == res.user and res.channel == ctx.channel
try:
res = await client.wait_for('buttonclick', check=check, timeout=30)
except asyncio.exceptions.TimeoutError:
tembed = discord.Embed(
title = 'Need More Time?',
descprtion = 'Try again once you\'ve had a chance to make your decision!',
color=Color.red())
await msg.edit(
embed=tembed,
components=[
Button(style=ButtonStyle.red,
label='Command Closed',
disabled=True)])
await asyncio.sleep(5)
await msg.delete()
return
if res.component.label == 'North':
member = ctx.author
mrole = discord.utils.find(lambda r:r.name == 'F1R1',ctx.message.guild.roles)
role = get(member.guild.roles, name='F1R1')
if mrole in member.roles:
await res.respond(content='You have a character in Room 1!')
await asyncio.sleep(3)
await msg.delete()
return
else:
await member.add_roles(role)
await asyncio.sleep(5)
await msg.delete()
return
else:
return
def setup(client):
client.add_cog(f1r4(client))
res = await client.wait_for('button_click', check=check, timeout=30) should be res = await self.client.wait_for('button_click', check=check, timeout=30).
There is also an typo on description for tembed.
Suggestions:
Don't import from discord_components.client. discord_components is supposed to export all required objects; using this breaks things if library decides to rename files.
buttons = DiscordComponents(client) should be DiscordComponents(client) in separate line.
I'm making a native language funny bot for my friends in my server... but I cant make it to play music... and that music ain't in YouTube, so I want to try anything other than YouTube … How to use SoundCloud for my discord bot python??? SoundCloud has it... how to import SoundCloud, pause it, play it, stop it etc. like rhythm bot???... I tried pyglet, but it doesn't play for everyone except me... I also used playsound module, still can't do it...
this is my code(ignore everything except all functions and modules used):
import discord
from discord.ext import commands
import os
import pyglet
######################################################################
player = pyglet.media.Player()
client = commands.Bot(command_prefix="-")
TOKEN = ""
#######################################################################
#client.event
async def on_ready():
print("singam kalayerangidichi!!!")
#client.command()
async def hi(ctx):
await ctx.send("hi bakthaa!!")
#client.command()
async def swamiji(ctx):
await ctx.send("kooptiyaa bakthaa?")
#client.command()
async def voicevaa(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#client.command()
async def udhavi(ctx):
embed = discord.Embed(title = "COMMANDS" , description = "command laam nalla paathu vechiko... ennaala thirumba thirumba solla mudiyaadhu..." , colour = discord.Colour.red())
embed.add_field(name = "-voicevaa" , value = "edhaa voice channel la nee poitu enna koopadrathukku..." , inline = True)
embed.add_field(name = "-kadha" , value = "sukaanubavam kekka use pannu..." , inline = True)
embed.add_field(name = "-wait" , value = "pesumbodhu unakku edhaa vela vandhaa, wait nu sollu... " , inline = True)
embed.add_field(name = "-ipposollu" , value = "wait pannavechitu apdiye poidaadha... konjam oda vidu..." , inline = True)
embed.add_field(name = "-niruthu" , value = "kadha pudikala naalo, vera kadha venum naalo, enna niruthu... apram adutha kadha povom..." , inline = True)
await ctx.send(embed = embed)
#client.command()#err
async def kadha(ctx):
embed = discord.Embed(title = "SUKAANUBAVAM" , description = "idhula edhaa oru kadhaya choose pannu bakthaa... naa solren..." , colour = discord.Colour.green())
embed.add_field(name = "KADHA" , value = "\n\n1.arrogant anaconda\n2.raja's revenge" , inline = True)
embed.set_footer(icon_url = ctx.author.avatar_url , text = f"kadha ketta bakthan {ctx.author.name} kaagha naan kudutha badhil...")
await ctx.send(embed = embed)
#client.command()
async def wait(ctx):
player.pause()
#client.command()
async def ipposollu(ctx):
player.play()
#client.command()
async def niruthu(ctx):
player.next_source()
#client.command()
async def anaconda(ctx):
player.next_source()
src0 = pyglet.media.load('aragont anaconda.mp3')
player.queue(src0)
player.play()
#client.command()
async def raja2(ctx):
player.next_source()
src1 = pyglet.media.load('rajas revenge.mp3')
player.queue(src1)
player.play()
#client.command()
async def kelambu(ctx):
await ctx.voice_client.disconnect()
player.next_source()
client.run(TOKEN)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I noticed that whenever a command is triggered, the bot usually takes a couple of seconds to respond. Is there any way I can increase the overall speed of the bot? I'm new to programming, so any insight would be greatly appreciated. Here is my code if it helps:
import discord
import os
import random
import praw
from keep_alive import keep_alive
from discord.ext import commands
from discord.ext.commands import Bot
import time
client = commands.Bot(command_prefix='.')
sec_triggers = ['just a sec', 'Just a sec', 'just a second', 'Just a second', 'one sec', 'one second', 'One sec', 'One second']
monke_triggers = ['monke', 'Monke', 'Monkey', 'monkey']
hello_triggers = ['hello there', 'Hello there', 'hello There', 'Hello There']
f_triggers = ['f in the chat', 'F in the chat', 'f in the Chat', 'F in the Chat']
colors = [0xff0000, 0xff3300, 0xff6600, 0xff9900, 0xffcc00, 0xffff00, 0xccff00, 0x99ff00, 0x66ff00, 0x33ff00, 0x00ff00, 0x00ff33, 0x00ff66, 0x00ff99, 0x00ffcc, 0x00ffff, 0x00ccff, 0x0099ff, 0x0066ff, 0x0033ff, 0x0000ff, 0x3300ff, 0x6600ff, 0x9900ff, 0xcc00ff, 0xff00ff, 0xff00cc, 0xff0099, 0xff0066, 0xff0033]
client.remove_command('help')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you, Wazowski. Always Watching. Always."))
#client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
if any(word in msg for word in monke_triggers):
await message.channel.send(file=discord.File('Reject Humanity, Return to Monke.jpg'))
if any(word in msg for word in sec_triggers):
time. sleep(1)
await message.channel.send("It's been one second")
if any(word in msg for word in hello_triggers):
await message.channel.send(file=discord.File('General_Kenobi.gif'))
if any(word in msg for word in f_triggers):
mention = message.author.name
await message.channel.send(f"{mention} had paid their respects.")
if message.content.lower() == 'f' or message.content.lower() == 'F':
mention = message.author.name
await message.channel.send(f"{mention} had paid their respects.")
await client.process_commands(message)
#client.command()
async def catjam(ctx, *, text):
message = f"{text}"
new_message = ""
for char in message:
new_message += f"<a:catjam:800476635655962644>{char}"
new_message += "<a:catjam:800476635655962644>"
await ctx.send(new_message)
await ctx.message.delete()
#client.command()
async def echo(ctx, *, text):
await ctx.send(f"{text}")
await ctx.message.delete()
#client.command()
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, text):
reason = f"{text}"
mention = ctx.message.author.name
pfp = member.avatar_url
em = discord.Embed(title = f"{member} has been kicked.", color = random.choice(colors))
em.add_field(name="Reason:", value=reason)
em.add_field(name="Responsible User:", value=mention)
em.set_thumbnail(url=(pfp))
await member.kick(reason=reason)
await ctx.send(embed=em)
#client.command()
#commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, text):
reason = f"{text}"
mention = ctx.message.author.name
pfp = member.avatar_url
em = discord.Embed(title = f"{member} has been banned.", description= f"__Reason:__ {reason} __Responsible moderator:__ {mention}", color = random.choice(colors))
em.set_thumbnail(url=(pfp))
await member.ban(reason=reason)
await ctx.send(embed=em)
#client.command()
async def comic(ctx):
subreddit = reddit.subreddit("comic")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def joke(ctx):
subreddit = reddit.subreddit("cleanjokes")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
text = random_sub.selftext
em = discord.Embed(title = name, color = random.choice(colors), description = text)
await ctx.send(embed = em)
#client.command()
async def meme(ctx):
subreddit = reddit.subreddit("cleanmemes")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def cat(ctx):
subreddit = reddit.subreddit("catpictures")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def dog(ctx):
subreddit = reddit.subreddit("dogpictures")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def help(ctx):
em = discord.Embed(color = random.choice(colors))
em.add_field(name='General Commands', value='__help__- Displays this message', inline=True)
await ctx.send(embed = em)
#client.command()
async def server(ctx):
server = ctx.message.guild
roles = str(len(server.roles))
emojis = str(len(server.emojis))
channels = str(len(server.channels))
embeded = discord.Embed(title=server.name, description='Server Info', color=random.choice(colors))
embeded.set_thumbnail(url=server.icon_url)
embeded.add_field(name="Created on:", value=server.created_at.strftime('%d %B %Y at %H:%M UTC+3'), inline=False)
embeded.add_field(name="Server ID:", value=server.id, inline=False)
embeded.add_field(name="Users on server:", value=server.member_count, inline=True)
embeded.add_field(name="Server owner:", value=server.owner, inline=True)
embeded.add_field(name="Server Region:", value=server.region, inline=True)
embeded.add_field(name="Verification Level:", value=server.verification_level, inline=True)
embeded.add_field(name="Role Count:", value=roles, inline=True)
embeded.add_field(name="Emoji Count:", value=emojis, inline=True)
embeded.add_field(name="Channel Count:", value=channels, inline=True)
await ctx.send(embed=embeded)
keep_alive()
client.run(os.getenv('TOKEN'))
(I am adding this part here because it won't let me revise the question otherwise. It tells me "Looks like your post is mostly code, please add some more details". So that is what I am doing, you don't need to read this part.)
This heavily depends on multiple factors.
Your code - I cannot help you without seeing your code, but in any case - a few seconds is a lot and better code wont really change that on a small scale
Your hardware - Also, this is a small part of your bot's performance, but should be negligible
(I think) it is your internet connection. Or maybe Discord's API is having trouble right now.
Of course, there are more factors to it, but it is most likely your internet connection.
If you are locally hosting your bot, then I am pretty much sure that it's your internet. I will show you an example.
Websocket latency when I host locally:
Websocket latency when I host with Heroku:
I experience late response too when I host locally, while with Heroku it's almost instant.
There are some commands which can take much longer than average commands (For example an aiohttp get/post session for uploading an image to Imgur, which takes about 5 seconds when I host locally, but comes almost instantly when I run with Heroku)