r/madeinpython • u/CotoCoutan • Jun 07 '20
Made a simple YouTube Timestamper bot in Telegram using Python.
2
u/-qarma- Jun 08 '20
This is awesome! Can you share the code?
1
u/CotoCoutan Jun 08 '20 edited Jun 08 '20
Sure! Here you go: (such a basic string interpolation thing, don't feel like posting on Github)
import requests import re import json from flask import Flask from flask import request from flask import Response from flask_sslify import SSLify token = "xxx" app = Flask(__name__) sslify = SSLify(app) def timestamper(txt): try: pattern = re.compile(" \d*") regexpCaptured = pattern.search(txt).group() #capturing the timestamp portion if len(regexpCaptured) != len(txt[28:]): # in case user types spaces or symbols between nos return f"\"{txt[0]} {txt[1:]}\" is in invalid format. Please send /start to see the accepted formats." #spacing out the txt variable so that Telegram doesn't show preview elif len(regexpCaptured) == 2: # when user types " 5" timestamp = f"{regexpCaptured[1]}s" url = f"https://www.youtube.com/watch?v={txt[17:28]}&t={timestamp}" return url elif len(regexpCaptured) == 3: # when user types " 35" timestamp = f"{regexpCaptured[1:]}s" url = f"https://www.youtube.com/watch?v={txt[17:28]}&t={timestamp}" return url elif len(regexpCaptured) == 4: # when user types " 435" timestamp = f"{regexpCaptured[1]}m{regexpCaptured[2:]}s" url = f"https://www.youtube.com/watch?v={txt[17:28]}&t={timestamp}" return url elif len(regexpCaptured) == 5: # when user types " 0435" timestamp = f"{regexpCaptured[1:3]}m{regexpCaptured[3:]}s" url = f"https://www.youtube.com/watch?v={txt[17:28]}&t={timestamp}" return url elif len(regexpCaptured) == 6: # when user types " 20435" timestamp = f"{regexpCaptured[1]}h{regexpCaptured[2:4]}m{regexpCaptured[4:]}s" url = f"https://www.youtube.com/watch?v={txt[17:28]}&t={timestamp}" return url elif len(regexpCaptured) == 7: # when user types " 220435". This will cover videos up to 99h99m99s. Longer videos YT doesn't support AFAIK. timestamp = f"{regexpCaptured[1:3]}h{regexpCaptured[3:5]}m{regexpCaptured[5:]}s" url = f"https://www.youtube.com/watch?v={txt[17:28]}&t={timestamp}" return url else: return f"\"{txt[0]} {txt[1:]}\" is in invalid format. Please send /start to see the accepted formats." except: return f"\"{txt[0]} {txt[1:]}\" is in invalid format. Please send /start to see the accepted formats." def write_json(data,filename='response.json'): with open(filename, 'w') as f: json.dump(data, f, indent = 4, ensure_ascii = False) def parsit(message): senderId = message['message']['from']['id'] chat_id = message['message']['chat']['id'] txt = message['message']['text'] senderName = message['message']['from']['first_name'] return chat_id, txt, senderId, senderName def send_message(chat_id, text='blablabla'): url = f'https://api.telegram.org/{token}/sendMessage' payload = {'chat_id':chat_id, 'text': text} r = requests.post(url,json=payload) return r @app.route('/', methods=['POST', 'GET']) #boilerplate code for Telegram bot waiting to hear from user. def index(): if request.method == 'POST': msg = request.get_json() write_json(msg,'telegram_incoming.json') # this is just if you want to refer the json file chat_id, txt, senderId, senderName = parsit(msg) if txt == "/start": send_message(chat_id, "Wannakum, message me only in either one of these formats: \n\"url hhmmss\"\n\"url hmmss\"\n\"url mmss\"\n\"url mss\"") return Response('Ok', status=200) output=timestamper(txt) send_message(chat_id, output) return Response('Ok', status=200) else: return '<h1>Shipping Spam Bot</h1>' if __name__ == '__main__': app.run(debug=True)The flask SSLify is so that it is compatible with PythonAnywhere, you can remove that if you're running it from your PC/localhost.
2
u/mohammadalimrg Jun 08 '20
Hey there Quick question:where do you host your bot?? I tried to code a bot on my own but I couldn't find a good server to host the code. It would be a great help for meπ π
1
u/CotoCoutan Jun 08 '20
Python Anywhere is AMAZING for free online hosting of these tiny codes :)
2
u/mohammadalimrg Jun 08 '20
I can't even express my appreciation Thanks
1
u/CotoCoutan Jun 08 '20
No worries man, ping me once your bot is up and running, would love to see what you create! :D
0
Jun 08 '20
[deleted]
2
u/CotoCoutan Jun 08 '20
Sorry, i guess i wasn't clear. If you want the timestamp of 126:15:45, you need to send "url 1261545". The '1261545' are not seconds, they're just a short way of writing '126h15m45s'.
I had originally thought of accepting delimited user input (like "126h15m45s", or "126:15:45", or "126 15 45") but in the end i felt it is much easier for the user to just type out the numbers without any delimiters.
3
u/CotoCoutan Jun 07 '20 edited Jun 08 '20
Try out the bot here: http://t.me/YouTubeTSBot
Made it due to the lack of the YT app to create timestamped URLs... and partly due to my own laziness. :P
Do note the bot accepts only the short URLs that you get when you tap on 'share' from the YouTube app. If you have the full URL already, you just need to type '&t=XmXs' at the end.
Edit - Sorry guys, didn't realize you could just append "?t=XmXs" to a short YT URL, I was made aware of this just now. I'll take down the bot, however short its life lol.
For long yt URLs use "&t=" whereas for short ones use "?t=".