OpenWeather API discord.py - discord

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!")

Related

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 Python Rewreite - Channel Searcher

So, i'm trying to make a YouTube channel search, I've made a simple code, but it didn't work, It always sends https://www.youtube.com/channel/v=XIDzSr3oX1w%22,%22webPageT, (Not a valid link),
The code is
#client.command()
async def channel(ctx, *, search):
query_string = urllib.parse.urlencode({
'search_query': search
})
htm_content = urllib.request.urlopen(
'https://www.youtube.com/results?' + query_string
)
search_results = re.findall(r'/watch\?v=(.{24})', htm_content.read().decode())
await ctx.send('https://www.youtube.com/channel/' + search_results[0])
You cannot parse the search results in youtube. Youtube is a dynamically generated website. If you want to actually parse youtube you will probably need to use youtube API or using python selenium.

Discord Python Rewrite - Move channel

Is it possible to move a channel on discord.py? Im making a nuke command that clones and deletes the channel, and it worked, but now i need to find out how to move the channel up to the origonal place, if there's a code / docs, please tell me a example. Thank's
Edit:
I Got a working edit but it's always drags it on top, i need it so it will drag the channel to the same position before it got nuked.
My code that i currently have
#client.command()
#commands.has_permissions(manage_channels=True)
async def nuke(ctx):
channel = ctx.channel
await channel.clone()
await channel.delete()
await channel.edit(position=0, sync_permissions=True)
return
You can use await channel.edit(position=0) to change the position. In this case, since 0 is specified, the channel will be moved to the first position.
If you want to move it to the deleted channel's position then you can check channel.position.
#client.command()
#commands.has_permissions(manage_channels=True)
async def nuke(ctx):
channel = ctx.channel
channel_position = channel.position
new_channel = await channel.clone()
await channel.delete()
await new_channel.edit(position=channel_position, sync_permissions=True)
return

Discord.py Bot issue with youtube-dl

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)

Resources