Telegram bot convert youtube link to mp3 (Python) - python-telegram-bot

How to make a telegram bot that converts simple youtube link (something like https://www.youtube.com/watch?v=v3F3v8yNucc) into .mp3?
Please suggest something with minimum efford

This will do the minimum job:
import os
import telebot
import youtube_dl
# get YOUR_API_KEY from #BotFather
bot = telebot.TeleBot("YOUR_API_KEY")
#bot.message_handler(commands=['start'])
def shoot(message):
bot.send_message(message.chat.id, "Gimme YouTube link")
#bot.message_handler()
def run(message):
if "https://www.youtube.com" not in message.text:
print("This is not YouTube link!")
return
bot.send_message(message.chat.id, "Please wait...")
video_info = youtube_dl.YoutubeDL().extract_info(
url = message.text, download=False
)
filename = f"{video_info['title']}.mp3"
options={
'format':'bestaudio/best',
'keepvideo':False,
'outtmpl':filename,
}
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download([video_info['webpage_url']])
print("Download complete... {}".format(filename))
bot.send_audio(message.chat.id, audio=open(filename, 'rb'))
bot.polling()
Thise code will download mp3 music to your server and sends it to the user in telegram, so you might wanna delete it after you send it, or need a larger server? Up to you.

Related

How to make my telegram-bot multi-threading?

I have a trouble. I need make my telegram-bot multi-threading. My bot will help users to buy films and will work with database. I use Webhooks-method for receiving requests from Telegram-server and Stripe(module request). I read a lot about threading module in python and about async functions but I am not sure for all 100% about how to make my bot multi-threading. I will very appreciated for help, because I am stuck on this question.
For now I give you main function of my app, if you need more, tell me:
#app.route('/', methods=["POST"])
def process():
print(request.json) # receiving requests (messages) in json format that are sent to the Flask server from the Telegram server and Stripe
if check_if_successful_payment(request) == True:
# Processing a request from Stripe
# chat_id = request.json["data"]["object"]["metadata"]["chat_id"]
stripe.api_key = get_from_env("PAYMENT_TOKEN")
webhook_list = stripe.WebhookEndpoint.list()
chat_id = webhook_list.data[0].metadata.chat_id
send_message(chat_id, "The payment was successful! Enjoy watching the movie!")
print("The payment was successful!")
webhook_id = webhook_list.data[0].id
stripe.WebhookEndpoint.delete(
webhook_id,
)
else:
# Processing a request from Telegram
chat_id = request.json["message"]["chat"]["id"]
send_message(chat_id, check_message(chat_id, request.json["message"]["text"]))
send_pay_button(chat_id=chat_id, text="Test payment",
price_id=check_price_id(request.json["message"]["text"]))
return {"ok": True}
if __name__ == '__main__':
app.run(debug=True)
If your bot works on Webhooks, you can use Aiogram instead of Flask for receiving messages from users. Aiogram has special decorator for simultaneous messages processing from many users - async_task: https://docs.aiogram.dev/en/latest/_modules/aiogram/dispatcher/dispatcher.html#Dispatcher.async_task

Attempting to rewrite a Discord.py GIF Bot from an old outdated guide

Ok, so I'm attempting to rebuild a GIF bot in Discord.py.
It is based off of some code found on a website that gave a guide on making a discord.py gif bot.
The problem is, the code is old and severely outdated with over 37 errors on it's own.
How would I go about converting this to discord.py-rewrite and basically making it a gif searching bot that can pick up random gifs by tag from GIPHY?
Here is the code I currently have:
import discord.utils
import os
import giphy_client
from giphy_client.rest import ApiException
from pprint import pprint
from discord.ext import commands
import random
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("GIPHY_API_KEY")
API_TOKEN = os.getenv("GIPHY_API_TOKEN")
api_instance = giphy_client.DefaultApi()
config = {
'api_key': API_KEY,
'token': API_TOKEN,
'limit': 1,
'rating': 'g'
}
try:
api_response = api_instance.gifs_trending_get(
config['token'], limit=config['limit'], rating=config['rating'])
pprint(api_response)
except ApiException as e:
print("Exception when calling DefaultApi->gifs_trending_get: %s\n" % e)
Client = commands.Bot(command_prefix=os.getenv("CLIENT_PREFIX"))
class DiscordClient(discord.Client):
#Client.event
async def on_ready(self):
print("Connected to Discord Client as")
print(f'{self.user.name}#{self.user.discriminator}')
print("-------")
#Client.command(name="gif")
async def search_gifs(query):
try:
giphy_token = API_TOKEN
response = api_instance.gifs_search_get(giphy_token, query, limit=3, rating='g')
lst = list(response.data)
gif = random.choices(lst)
return gif[0].url
except ApiException as e:
return "Exception when calling DefaultApi->gifs_search_get: %s\n" % e
async def on_ready(self):
print("Connected to Discord Client as")
print(Client.user.name)
print("-------")
#Client.command(name='gif')
async def search_gifs(query):
try:
response = api_instance.gifs_search_get(
API_TOKEN, query, limit=3, rating='g')
lst = list(response.data)
gif = random.choices(lst)
return gif[0].url
except ApiException as e:\
return "Exception when calling DefaultApi->gifs_search_get: %s\n" % e\
#Client.command(name='8ball')
async def magic_eight_ball(ctx):
response = [
'Without a doubt.',
'Outlook good.',
'Better not tell you now.',
'Cannot predict now.',
'My reply is no.',
'Outlook not so good.',
]
gif = await search_gifs('cheese')
await ctx.send(random.choice(response))
await ctx.send('Gif URL : ' + gif)
Client.run(os.getenv("CLIENT_TOKEN"))
Here is the website I got the code I'm building off of from:
https://www.maxongzb.com/serving-gifs-with-discord-bot-reading-time-12-mins/
Here is what I currently have for the requirements.txt file:
discord.py
giphy_client
python-dotenv
Any help would be much appreciated.
I host via Heroku due to my VPS taking a dump, so that's why I have the os.getenv("...") lines in there.
I've gotten it down to around 7 errors, 8 warnings and 8 weak warnings. But that's the furthest I was able to get to.

Copy a discord user's avatar and nickname to bot

I am trying to make a joke bot that basically "steals" his nickname and avatar but I've had no success
#tasks.loop(minutes=.01)
async def avatar(*, member: discord.Member = None):
member = client.get_user(id=<id>)
userAvatar = discord.Member.avatar_url
bot.user.edit(avatar=userAvatar)
That's the code that I have done, You have to create 2 folders Avatars/Steal_av
and then what this code does is that it gets the user's avatar and stores it in Stolen.png then sets it as his avatar/PFP, but you have to get his password and put it in a config file, without the password it doesn't work.
If you still need me to tell you how to do the steal nickname tell me but I thought you won't want it since I told you that it doesn't work unless you have his password.
#Imports
import requests
from PIL import Image
with open('Avatars/Steal_av/Stolen.png', 'wb') as f:
r = requests.get(user.avatar_url, stream=True)
for block in r.iter_content(1024):
if not block:
break
f.write(block)
Image.open('Avatars/Steal_av/Stolen.png').convert('RGB')
with open('Avatars/Steal_av/Stolen.png', 'rb') as f:
await client.user.edit(password=password, avatar=f.read())

discord.py how to connect random choices

I'm trying to make a meme command (where random images come out) personally dedicated to the server and I would like the author of the meme to be mentioned.
But I'm afraid that if I also create images for the author other than the author.
My question is essentially:
How do I put both the image and the author in the same variable? (Sorry if I explained myself wrong)
Code
#random image embed
#client.command(aliases=["IM","im"])
async def image_embed(ctx):
tartufo=[
'https://cdn.discordapp.com/attachments/640563710104043530/731555200489357362/salvenee.jpg',
'https://cdn.discordapp.com/attachments/640563710104043530/731552604546662511/unknown.png',
'https://media.gettyimages.com/photos/rocks-balancing-on-driftwood-sea-in-background-picture-id153081592?s=612x612'
]
embed = discord.Embed(
color=discord.Colour.dark_blue()
)
embed.set_image(url=random.choice(tartufo))
embed.set_footer(text=f'Richiesto da {ctx.author.name}')
await ctx.send(embed=embed)
You can make a list of tuples where the elements of each tuple are the url and author:
images = [
('url1', 'author1'),
('url2', 'author2'),
('url3', 'author3'),
('url4', 'author4'),
]
url, author = random.choice(images)
embed.set_image(url=url)
embed.set_footer(text=f'Author is {author}')

How to download the image of an embeded message with disord.py

I am trying to be able to download the content of an embedded message.
This is what I am running so far
async def on_message(self, message):
embedFromMessage = message.embeds
print(embedFromMessage)
I would like it to output the url of the attached image and the description but is only outputting [discord.embeds.Embed object at 0x049A8990]
The discord.py API provides you a set of tools to allowing you to find what you're looking for.
Find the embed
As I see you're trying to catch an embedded message using the on_message event.
To do so we're going to use this :
#commands.Cog.listener()
async def on_message(self, message):
if(len(message.embeds) > 0):
This simple if statment will determine if the message is an embedded one or not.
If the message is an embed it will return a list of embeds.
Note that the image preview is considered as an embedded message.
Now let's catch the embed you want :
_embed = message.embeds[0] # this will return the first embed in message.embeds
Once we've stored the embed, we want to know if it contains an image :
if not _embed.image.url == discord.Embed.Empty:
image = _embed.image.url
By default, _embed.image will return an EmbedProxy which looks like that :
EmbedProxy(width=0, url='URL', proxy_url='PROXY_URL', height=0)
To access the value of url we have done _embed.image.url.
Now you have the image URL, you can download it using the aiohttp library for example.
The full code
Here is the code you can use to catch the image inside an embedded message as those that are created using the discord.Embed() class.
#commands.Cog.listener()
async def on_message(self, message):
if(len(message.embeds) > 0):
_embed = message.embeds[0]
if not _embed.image.url == discord.Embed.Empty:
image = _embed.image.url
channel = message.channel # get the channel where the embed has been sent
await channel.send(image) # send the image into the channel
Hope it helped !
Have a nice day !

Resources