Discord.py Bot issue with youtube-dl - discord

I'm having a strange issue with my discord bot. Up until today all was fine but all of a sudden when I use my >play command with a search query like >play spiderman pizza for example I get 'WARNING:root:NoneType: None' right when the video is about to play. If I use a URL after the >play command, it still works flawlessly as it did before. I've looked and I just cant see the issue. This is the main code of my play command with stuff like the queuing system and permission checking taken out as it's not related.
#client.command(pass_context=True)
async def play(ctx,*, url):
server = ctx.message.server
voice_client = client.voice_client_in(server)
player = await voice_client.create_ytdl_player(url, ytdl_options={'default_search': 'auto'}, after =lambda: check_queue(server.id))
players[server.id] = player
player.volume = 0.18
embed=discord.Embed(title=("⏬ Audio downloaded succesfully ⏬"), color=0x9400D3)
await client.say(embed=embed)
await asyncio.sleep(0.2)
embed=discord.Embed(title=(player.uploader), description=(player.description), color=0x9400D3)
embed.set_author(name=(player.title), url=(player.url) , icon_url='https://upload.wikimedia.org/wikipedia/commons/7/73/YouTube_Music.png')
embed.add_field(name="Duration(in seconds):", value=(player.duration), inline=True)
embed.add_field(name="Current Views:", value=(player.views), inline=True)
embed.add_field(name="Likes:", value=(player.likes), inline=True)
embed.add_field(name="Dislikes:", value=(player.dislikes), inline=True)
embed.set_footer(text=random.choice(messages))
await client.say(embed=embed)
players[server.id] = player
player.start()
await asyncio.sleep(0.2)
embed=discord.Embed(title=("🎶 Now Playing 🎶"), color=0x9400D3)
await client.say(embed=embed)

Related

In discord.py when I use more than 1 `on_message` it does not works, only the last one works

This is my code, and on_message is not working when used twice, only the 2nd one is working. Please help me.
async def on_message(message):<br>
if message.content.startswith('-coinflip'):<br>
embedVar = discord.Embed(<br>
title="Toss",<br>
description=(f'You got {random.choice(heads_tails)}'),<br>
color=(0xFF0000))<br>
print(f'-coinflip command used by {message.author}')<br>
await message.channel.send(embed=embedVar)<br>
#client.event<br>
async def on_message(message):<br>
if message.content.startswith('-help'):<br>
embedVar = discord.Embed(<br>
title="Help arrived!",<br>
description="So, it looks like you need help, let me help you",<br>
colour=0xFF0000)<br>
embedVar.add_field(name="Bot Prefix", value="-", inline=False)<br>
embedVar.add_field(name="Moderation Commands",<br>
value="-help",<br>
inline=True)<br>
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)<br>
embedVar.set_thumbnail(<br>
url=<br>
"https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif"<br>
)<br>
print(f'-help command used by {message.author}')<br>
await message.channel.send(embed=embedVar)<br>```
Here's the answer I wrote but couldn't post:
You cannot have 2 on_message event listeners. You can merge the two event listeners and their responses by using if...elif like this instead:
#bot.event
async def on_message(message): #When any message is sent
if message.content.startswith('-coinflip'):
embedVar = discord.Embed(
title="Toss",
description=f'You got {random.choice(heads_tails)}',
color=(0xFF0000))
print(f'-coinflip command used by {message.author}')
await message.channel.send(embed=embedVar)
elif message.content.startswith('-help'):
embedVar = discord.Embed(
title="Help arrived!",
description="So, it looks like you need help, let me help you",
colour=0xFF0000)
embedVar.add_field(name="Bot Prefix", value="-", inline=False)
embedVar.add_field(name="Moderation Commands",
value="-help",
inline=True)
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)
embedVar.set_thumbnail(
url="https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif")
print(f'-help command used by {message.author}')
await message.channel.send(embed=embedVar)
elif is the same as else if; in this case, if the message's content doesn't start with "-coinflip" and starts with "-help", it creates and sends an Embed.
I've replaced the heads_tails variable for a fully-functioning code:
from discord.ext import commands
import discord
import discord.utils
import random
intent = discord.Intents(messages=True, message_content=True, guilds=True)
bot = commands.Bot(command_prefix="", description="", intents=intent)
heads_tails = ("Heads", "Tails") #Replace this with your sequence
#bot.event
async def on_ready(): #When the bot comes online
print("It's online.")
#bot.event
async def on_message(message): #When any message is sent
if message.content.startswith('-coinflip'):
embedVar = discord.Embed(
title="Toss",
description=f'You got {random.choice(heads_tails)}',
color=(0xFF0000))
print(f'-coinflip command used by {message.author}')
await message.channel.send(embed=embedVar)
elif message.content.startswith('-help'):
embedVar = discord.Embed(
title="Help arrived!",
description="So, it looks like you need help, let me help you",
colour=0xFF0000)
embedVar.add_field(name="Bot Prefix", value="-", inline=False)
embedVar.add_field(name="Moderation Commands",
value="-help",
inline=True)
embedVar.add_field(name="Fun commands", value="-coinflip", inline=True)
embedVar.set_thumbnail(
url="https://media.discordapp.net/attachments/923531605660815373/974248483479494686/charizard-mega-charizard-y.gif")
print(f'-help command used by {message.author}')
await message.channel.send(embed=embedVar)
Also, is "-help" a moderation command? And, try searching for and solving such problems yourself. StackOverflow shouldn't be the first place to ask such questions.

discord.py sending message to channel name instead of ID

I am a beginner to this programming stuff, and I have a quick question. I am trying to make a logs channel for multiple servers, and I want to be able to look for a channel that has the word “logs” in it, so can you help me?
Code:
#client.event
async def on_command_completion(ctx):
channel = client.get_channel('829067962316750898')
embed = discord.Embed(colour=discord.Color.green(),
title="Command Executed")
embed.add_field(name="Command:", value=f"`,{ctx.command}`")
embed.add_field(name="User:", value=f"{ctx.author.mention}", inline=False)
embed.add_field(name="Channel:",
value=f"{ctx.channel} **( <#{ctx.channel.id}> )**")
await channel.send(embed=embed)
You need to get the channel. I suggest using discord.utils.get.
Also, try using {ctx.channel.mention} to mention the channel instead.
#client.event
async def on_command_completion(ctx):
channel = discord.utils.get(ctx.guild.text_channels, name='logs')
if channel is None:
return # If there is no logs channel, do nothing (or what you want to do)
embed = discord.Embed(colour=discord.Color.green(),
title="Command Executed")
embed.add_field(name="Command:", value=f"`,{ctx.command}`")
embed.add_field(name="User:", value=f"{ctx.author.mention}", inline=False)
embed.add_field(name="Channel:",
value=f"{channel.name} **( {channel.mention} )**")
await channel.send(embed=embed)
See the discord.TextChannel docs and discord.utils.get()

Why my discord bot goes offline when running a loop

Hello i have a problem with my discord bot. I'm new to python and also very new to creating my own bot, and I couldn't find an answer to my problem. Iam running a discord bot that checks the availability of stocks on a specific web site. And when i use a "While true: ... time.sleep(60)" loop to refresh and download the data from the web site my bot just shows offline on a discord server. I tried to change the timer to longer and also tried to print and send some messages to a discord. And i found out that even when the bot is offline it can send message and everything. No errors or any warning everything works but the bot is offline. If there is somebody who could help me out with my problem or heard about it. I would appreciate it a lot. I can share the code if there is somebody who has a little bit of time to help me.
Code:
while True:
Zoznam.clear()
hodnoty = nacitaniehodnot()
produkt = hodnoty[0]
obrazok = hodnoty[1]
pocetpoloziek = hodnoty[2]
shopy = ''
cennik = ''
for i in Zoznam:
shopy = shopy+i[0]+'\n'
cennik = cennik+i[1]+'\n'
embed = discord.Embed(title =produkt,color= 0x008FFF)
embed.set_thumbnail(url=obrazok)
embed.set_author(name='Heureka', url=url,icon_url="https://i1.wp.com/blog.heureka.sk/wp-content/uploads/2019/12/cropped-lupa_heureka_rgb-01.png?fit=512%2C512&ssl=1&w=640")
embed.add_field(name="Obchod", value=shopy, inline=True)
embed.add_field(name="Cena", value=cennik, inline=True)
#embed.add_field(name="Doprava", value=doprava, inline=True)
global sprava
if pocetpoloziek != y and sprava is not None:
await sprava.delete()
sprava = await channel.send(embed=embed)
i=y
elif not sprava:
sprava = await channel.send(embed=embed)
time.sleep(30)
The problem is likely due to time.sleep since time.sleep is not asynchronous and will block all commands during the sleep time.
Try importing asyncio import asyncio and using await asyncio.sleep(30) instead since it won't block other commands from running during the sleep time.

DISCORD PY: How to store user input into a variable?

I am currently creating a simple login system for my discord server and im trying to find a way to store the user input into a variable and using it for a database. I currently want the input of [https://steamcommunity.com/id/] in the variable.
async def on_message(message):
if message.content.startswith('!login'):
channel = message.channel
embed = discord.Embed(color=discord.Color.red())
embed.set_author(name='{0.user}'.format(client), icon_url='https://scontent.fsyd1-1.fna.fbcdn.net/v/t1.15752-9/119154591_373692013645493_2520568812144261390_n.png?_nc_cat=100&ccb=2&_nc_sid=ae9488&_nc_ohc=qee8e9Q3a0sAX9_z2Nj&_nc_ht=scontent.fsyd1-1.fna&oh=ffeafaaa09f2bb802afce08030c41f08&oe=60394D0B')
embed.add_field(name='WELCOME TO LINKED.GG', value='Looking forward to seeing you in queue!', inline=False)
embed.add_field(name='Link your STEAM account to the bot:',
value='Reply to this bots message: \n `!login <steam profile url>`', inline=False)
embed.add_field(name='Please read over the rules:',
value='<#804911670698442815>', inline=False)
embed.add_field(name='Join our discord server', value='[Click to join discord](https://discord.gg/2dKCUAzceN)', inline=True)
await channel.send(embed=embed)
def check(m):
return m.content.startswith('https://steamcommunity.com/id/') and m.channel == channel
msg = await client.wait_for('message', check=check)
print(msg)
await channel.send('Connected {.author}!'.format(msg))
await client.process_commands(message)```
It's better by using a command instead of an on_message then you can pass an argument with the logging command. Ill leave it up to you to get your database sorted out, and searching if an account was already created.
Below is a simple example of passing a "username" argument through the command, the username would then be stored within the username variable.
#client.command()
async def login(ctx, *, username=None):
if username == None:
await ctx.send(f'{ctx.author.mention}, please enter your username to log in!')
return
await ctx.send(f'Logged in as {username}! Welcome back.')

OpenWeather API discord.py

I recently came around OpeNweather API and I made a simple current weather command with help of this post: How to make a weather command using discord.py v1.4.1
I am pretty new to API so I need help with using Forecast API (documentation can be found here https://openweathermap.org/api/hourly-forecast)
I am using discord.py Rewrite for my bot
thanks for inspiration of making this command. But with a little research and more details/learning how to retrieve data back from the API, got me here. I would like to help and share with you what I have come up with.
Basically, I used all the features available from the API. In my code below, it will look for temperature, humidity and pressure in the air. It uses a "get" method to retrieve this data, conditional that a valid city was provided in the command.
Simply get the key from the site and copy & paste in the "api_key" string. Hope this helps with your progress and though I may as well help out as I got the command working well.
api_key = "123abcmyweathercodeapitoken"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
#client.command()
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message.channel
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
current_temperature_celsiuis = str(round(current_temperature - 273.15))
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
embed = discord.Embed(
title=f"Weather forecast - {city_name}",
color=0x7289DA,
timestamp=ctx.message.created_at,
)
embed.add_field(
name="Description",
value=f"**{weather_description}**",
inline=False)
embed.add_field(
name="Temperature(C)",
value=f"**{current_temperature_celsiuis}°C**",
inline=False)
embed.add_field(
name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(
name="Atmospheric Pressure(hPa)",
value=f"**{current_pressure}hPa**",
inline=False)
embed.set_footer(text=f"Requested by {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send(
f"There was no results about this place!")

Resources