Discord.py Lyrics command issue - python

I have made this lyrics search command and it works well. The problem is most of the lyrics that are returned are over 2000 characters. How can I make a new embed for this and continue the lyrics?
#bot.command()
async def lyrics(ctx , * , q):
genius = Genius('abcxyz')
song = genius.search_song(q)
em = discord.Embed(title = 'Here is the result -' , description = song.lyrics)
#await ctx.send(song.lyrics)
await ctx.send(embed = em)

you can do something like this:
lyrics = "*Your Lyrics*"
part1 = lyrics[1999]
and send part1, and to get part2
part2 = lyrics[:lyrics-part1] # or something like that

Related

Nextcord Discord Bot, Use API with Pexels API to get random images

Just like the title, I'm wanting to use the pexels api in a slash command to get random images from pexels (or any other site) using nextcord bot, hosting on repl.it. Begging for guidance, thank you in advance. See code below
async def init(interaction: Interaction):
await interaction.response.defer()
async with aiohttp.ClientSession()as session:
async with session.get(url = "https://api.pexels.com/v1/curated", headers = {'Authorization': "23456789"}, data = {"per_page": "1"}) as response:
raw = await response.text()
raw = raw.replace('[', '').replace(']', '')
init = json.loads(raw)
url = init["url"]
myobj = {'per_page':'1'}
embed = nextcord.Embed(page = init["page"], timestamp = datetime.now(), color = nextcord.Colour.green())
try:
embed.add_field(name = "Copyright", value = init["copyright"])
except KeyError:
pass
embed.set_image(url = url, myobj = myobj)
embed.set_footer(text = f"From {init['date']}")
await interaction.followup.send(embed = embed)

Cant reply json on discord.py

Im making a cripto price tracker and i cant make it reply the json that im making with the coin decko URL and Arg1 for example Eternal or SLP, etc.
# bot = scrt.bot
bot = commands.Bot(command_prefix = "!")
login = 0
tokens_dict = {
'morw' : '0x6b61b24504a6378e1a99d2aa2a5efcb1f5627a3a',
'slp' : '0xcc8fa225d80b9c7d42f96e9570156c65d6caaa25',
'pvu' : '0x31471e0791fcdbe82fbf4c44943255e923f1b794',
'eternal' : '0xd44fd09d74cd13838f137b590497595d6b3feea4'
}
# Login
#bot.event
async def on_ready():
global login
print('We have logged in as {0.user}'.format(bot))
login = 1
#bot.command()
async def coin(ctx, arg1):
global tokens_dict
if(arg1 in tokens_dict.keys()):
url = 'https://api.pancakeswap.info/api/v2/tokens/' + tokens_dict[arg1]
response = request.get(url)
responseDict = json.loads(response.text)
await ctx.reply(responseDict)
else:
await ctx.reply("The token " + str(arg1) + " is not in the token list, if you want to add " + str(arg1) + " to the list please use the command : " + '\n' + "!add_token")
In the coin function im trying to reply the json that ive created but i dont know how to.
response = request.get(url)
responseDict = json.loads(response.text)
await ctx.reply(responseDict)
I'm assuming this is the part you're talking about.
You actually don't need to call json.loads(response.text) if you're going to send it anyway. If the raw response is unformatted then you can do this
response_dict = json.loads(response.text)
formatted_dict = json.dumps(response_dict, indent=4)
await ctx.reply(formatted_dict)
This should send the json as a string with indents.
The reason discord.py wasn't letting you send the message was because it wasn't a string.

Youtube search command doesnt work (Discord.py)

I have made youtube search command in discord.py but for some reason the bot only sends main page of youtube but not the term i want to search.
My code:
#bot.command()
#commands.cooldown(1, 60.00, commands.BucketType.guild)
async def yt(msg, *, search):
query_string = urllib.parse.urlencode({
"search_query": search
})
html_content = urllib.request.urlopen(
"http://www.youtube.com/results?" + query_string
)
search_results = re.findall(r"watch\?v=(\S{11})", html_content.read().decode())
await msg.send("http://www.youtube.com/watch?v" + search_results[0])
change this:
await msg.send("http://www.youtube.com/watch?v" + search_results[0])
to this:
await msg.send("http://www.youtube.com/watch?v=" + search_results[0])

Discord.py list users in a message when reaction

i have been trying to fix a problem for days. I want to send an embet naricht and this should be edited as soon as someone has made a reaction.
here my snipped code:
embed = discord.Embed(title='General Information', color=16769251)
embed.set_footer(text='General information')
embed.set_thumbnail(url=message.guild.icon_url)
embed.add_field(name='Text Header ', value=all_lines[1], inline=False)
embed.add_field(name='Text Header 2: ', value=all_lines[2], inline=False)
embed.add_field(name='Accepted Users: ', 'HERE ALL USERS WITH ✅', inline=False)
mess = await message.send(embed=embed)
await mess.add_reaction('✅')
await mess.add_reaction('❌')
I have already tried a lot of things but unfortunately without success I think it would be just too much to really put everything in here I still hodde that someone can help me
Here an example :
Before ( without reactions )
https://i.gyazo.com/1518bc2bfe8b55e2e790ff6481c261f7.png
After with reactions:
https://i.gyazo.com/8bf97513e1eaf567ca9dda66f54fa2f0.png
Final Version with 1 little refresh bug:
async def ReportRaid(self, message, bot):
name = message.author
if message.author.bot:
return
else:
await message.delete()
args = message.content.split(' ')
# raid <type> <name> <setting> <min>
# 0 1 2 3 4
if args[0] == "/raid" or args[0] == "/Raid":
embed = discord.Embed(title='Raid meldung von ' + str(message.author.display_name))
embed.add_field(name='Raid Typ: ', value=args[1], inline=True)
embed.add_field(name='Name: ', value=args[2], inline=True)
embed.add_field(name=settings.RaidSetings[args[3]], value=args[4] + " Minuten", inline=True)
embed.add_field(name='Zusagen:', value='Keine Zusagen', inline=True)
if not args[2].lower() in pkm.pokeDir[args[1].lower()]:
await message.channel.send('Das pokemon konnte nicht gefunden werden.', delete_after=30.0)
return
else:
embed.set_thumbnail(
url=settings.ServerSettings["ImageURL"] + pkm.pokeDir[args[1].lower()][args[2].lower()] + '.png')
try:
with open('accounts/Ac' + str(name) + '.txt', "r") as fp:
all_lines = fp.readlines()
embed.set_footer(text='Trainer name: {} \nTrainer Code: {}'.format(all_lines[1], all_lines[3]))
tgName = all_lines[3]
except IOError:
embed.set_footer(text='Keine Informationen gefunden')
tgName = "Keinen Trainer code gefunden"
channel = bot.get_channel(int(await guild_setings.LoadGuildSettings().get_raid_channel(message)))
mess = await channel.send(embed=embed, delete_after=int(args[4]) * 60)
tg.TelegramBot(message, '**\nRaid Typ: ' + args[1] + "\nName: " + args[2] + "\n" + settings.RaidSetings[args[3]] + " " + args[4] + ' Minuten\nTriainer Code: ' + tgName + '\nRaid Meldung von: ' + str(message.author.display_name)).SendToTelegramm()
re_time = int(args[4]) * 60
emoji_list = ['✅', '❌']
for i in emoji_list:
await mess.add_reaction(i)
while True:
users = ""
try:
reaction, user= await bot.wait_for("reaction_add", timeout=re_time)
if str(reaction) == '✅':
mess = await channel.fetch_message(mess.id)
reaction_list = mess.reactions
for reactions in reaction_list:
if str(reactions) == "✅":
user_list = [user async for user in reactions.users() if user != bot.user]
for user in user_list:
users = users + user.mention + "\n"
embed_1 = discord.Embed(title='Raid meldung von ' + str(message.author.display_name))
embed_1.add_field(name='Raid Typ: ', value=args[1], inline=True)
embed_1.add_field(name='Name: ', value=args[2], inline=True)
embed_1.add_field(name=settings.RaidSetings[args[3]], value=args[4] + " Minuten", inline=True)
embed_1.add_field(name='Zusagen:', value=users, inline=True)
if not args[2].lower() in pkm.pokeDir[args[1].lower()]:
await message.channel.send('Das pokemon konnte nicht gefunden werden.', delete_after=30.0)
return
else:
embed_1.set_thumbnail(
url=settings.ServerSettings["ImageURL"] + pkm.pokeDir[args[1].lower()][args[2].lower()] + '.png')
try:
with open('accounts/Ac' + str(name) + '.txt', "r") as fp:
all_lines = fp.readlines()
embed_1.set_footer(text='Trainer name: {} \nTrainer Code: {}'.format(all_lines[1], all_lines[3]))
except IOError:
embed_1.set_footer(text='Keine Informationen gefunden')
await mess.edit(embed = embed_1)
except asyncio.TimeoutError:
break
If I understand you correctly, you want something like this. I've tried putting comments in the code along the way so you can understand better what's going on.
As the code is right now, it will not update if a user removes the reaction. If user_1 and user_2 adds reaction, and then user_1 removes reaction, they will both still show, when user_3 adds reaction, it will update to show only user_2 and user_3
You can add the code between *** in the exception as well, to update the embed one final time as the loop ends.
Another thing is that I don't know what your all_lines is, so I had that just as a string during testing.
#client.command() # Correct this according to your code, if you're using bot or client
async def rtest(ctx):
message = ctx.message
# At first we create create the embed
embed = discord.Embed(title='General Information', color=16769251)
embed.set_footer(text='General information')
embed.set_thumbnail(url=message.guild.icon_url)
embed.add_field(name='Text Header ', value=all_lines[1], inline=False)
embed.add_field(name='Text Header 2: ', value=all_lines[2], inline=False)
embed.add_field(name='Accepted Users: ', value='HERE ALL USERS WITH ✅', inline=False)
mess = await ctx.send(embed=embed)
# And add our reactions to the embed
emoji_list = ['✅', '❌']
for i in emoji_list:
await mess.add_reaction(i)
# Create a while loop that will wait for users to react
while True:
users = "" # Create empty string that we need later
try:
reaction, user= await client.wait_for("reaction_add", timeout=60)
# Check that if the reaction added is ✅, and if it is:
if str(reaction) == "✅":
mess = await ctx.channel.fetch_message(mess.id) #*** Need to fetch message again to get updated reaction information
reaction_list = mess.reactions
# Check our reactions on the message, get user list for the ✅ reaction, ignoring the bot
for reactions in mess.reactions:
if str(reactions) == "✅":
user_list = [user async for user in reactions.users() if user != client.user]
# Update the users string, to add user that reacted
for user in user_list:
users = users + user.mention + "\n"
# Create an updated embed with different name, it's the same as before, but with users in last field
embed_1 = discord.Embed(title='General Information', color=16769251)
embed_1.set_footer(text='General information')
embed_1.set_thumbnail(url=message.guild.icon_url)
embed_1.add_field(name='Text Header ', value=all_lines[1], inline=False)
embed_1.add_field(name='Text Header 2: ', value=all_lines[2], inline=False)
embed_1.add_field(name='Accepted Users: ', value='HERE ALL USERS WITH ✅\n'+users, inline=False)
await mess.edit(embed = embed_1) # Edit message to be the updated embed
#***
# End the loop after the set amount of time (from timeout earlier)
except asyncio.TimeoutError:
break
What you're looking for is bot.wait_for, here a simple example
#bot.command()
async def react(ctx):
# Sending the message
message = await ctx.send('React with ✅')
def check(reaction, user):
# Checking if the user that reacted is the same as the one that invoked the command
# also checking if the reaction is `✅` and if the reacted message is the one sent before
return user == ctx.author and str(reaction) == '✅' and reaction.message == message
try:
# Waiting for the reaction
reaction, user = await bot.wait_for('reaction_add', check=check, timeout=60.0)
except asyncio.TimeoutError:
# If the timeout is over, deleting the message
await message.delete()
await ctx.send('Timeout is over')
else:
# If the reaction is not the one we're waiting for, send this
await ctx.send('Bad reaction')
Reference

Problem with importing discord.py modules

StackOverflow.
I've been having a problem with a discord bot, here's the script:
def send():
url = "https://discordapp.com/api/webhooks/762125650546131005/lgYkjh-ILrag2sb3nzqUZfF1sg2mN2a0QeABaUq9dwl7qBTNL4EqWV00K62xWZ8_sNQ5"
data = {}
data["content"] = ""
data["username"] = "Suggestions"
data["embeds"] = []
embed = {}
embed["description"] = "**Author** » <#" + str(message.author.id) + ">\n **Suggestion** » " + str(args)
embed["title"] = "**New Suggestion!**"
data["embeds"].append(embed)
result = requests.post(url, data=json.dumps(data), headers={"Content-Type": "application/json"})
send()
await message.author.send("Thank you for your suggestion! We will look into it as soon as possible and will message you if it will be used.")
When I do ";suggestion fix bugs" it just sends to the webhook "fix" which is only the first word and I am struggling to fix this. Please may someone help?
Don't use requests with discord.py, it is sync and will block your bot, use a discord.Webhook with aiohttp to send a discord.Embed
Example:
from aiohttp import ClientSession
async with ClientSession() as session:
wh = discord.Webhook.from_url("<webhook url>", adapter=discord.AsyncWebhookAdapter(session))
e = discord.Embed()
e.title = "Hello I am an Embed"
...
await wh.send(embed=e)

Categories