-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbot.py
205 lines (169 loc) · 6.82 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
from __future__ import unicode_literals
from telegram import *
from telegram.ext import *
from random import randint
from html.parser import HTMLParser
from bs4 import BeautifulSoup
from lxml import etree
import urllib.request, json, requests, time, urllib.parse, os, urllib, lxml, youtube_dl
GET_CDICE = range(1)
GET_DOWNLOADMUSIC1, GET_DOWNLOADMUSIC2 = range(2)
def start(bot, update):
update.message.reply_text(
"Hiiiiiii!\nI'm Mr. MeeTube, look at me!\n"
"So, what can you do?\n\n"
"/song - Get a song from YouTube!\n"
"\nMiscellaneous:\n"
"/coin - Flip a coin\n"
"/dice - Roll a dice\n"
"/cdice - Roll a custom dice")
def asksong(bot, update):
update.message.reply_text("What's the song you're looking for?")
return GET_DOWNLOADMUSIC1
def downloadmusic(bot, update, user_data):
lastmsg = update.message.text
update.message.reply_text('Searching...')
try:
query = urllib.parse.quote(lastmsg)
url = ("https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q={}".format(query))
response = urllib.request.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
titles = []
links = []
for n in range(0,3):
linkyt = soup.findAll(attrs={'class':'yt-uix-tile-link'})[n]['href'].replace("watch?v=","")
truelink = 'https://youtu.be' + linkyt
links.append(truelink)
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == 'title':
self.found = True
def handle_data(self, data):
if self.found == True:
titles.append(data.replace(' - YouTube',''))
self.found = False
fp = urllib.request.urlopen(truelink)
mybytes = fp.read()
mystr = mybytes.decode("utf8")
fp.close()
parser = MyHTMLParser()
parser.found = False
parser.feed(mystr)
messagetosend = 'Please select a number:\n'
i = 1
for n in titles:
messagetosend += '{}. {}\n'.format(i, n)
i += 1
messagetosend = messagetosend.strip()
messagetosend += '\n\n4. To cancel!'
messagetosend = messagetosend.strip()
update.message.reply_text(messagetosend)
user_data['titles'] = titles
user_data['links'] = links
return GET_DOWNLOADMUSIC2
except:
update.message.reply_text('An error ocurred! Sorry for the inconvenience!!')
return ConversationHandler.END
def downloadmusic_response(bot, update, user_data):
user = update.message.from_user['username']
lastmsg = update.message.text
choice = 0
if lastmsg.strip() == '1':
choice = 0
elif lastmsg.strip() == '2':
choice = 1
elif lastmsg.strip() == '3':
choice = 2
elif lastmsg.strip() == '4':
update.message.reply_text("Canceled! Look at me!!")
return ConversationHandler.END
else:
update.message.reply_text("That isn't an option! Please choose 1, 2, 3 or 4!!")
return GET_DOWNLOADMUSIC2
musictitle = user_data['titles'][choice]
musiclink = user_data['links'][choice]
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': '{}/music.mp3'.format(user),
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
update.message.reply_text('Downloading...')
ydl.download([musiclink])
if os.path.getsize('{}/music.mp3'.format(user)) < 50000000:
os.rename('{}/music.mp3'.format(user),'{}/{}.mp3'.format(user,musictitle))
update.message.reply_text('Okay, here it is!')
bot.send_audio(chat_id=update.message.chat_id, audio=open('{}/{}.mp3'.format(user,musictitle), 'rb'))
else:
update.message.reply_text("I'm sorry but the song you requested is larger than telegram's max size limit, 50MB")
os.remove('{}/{}.mp3'.format(user,musictitle))
return ConversationHandler.END
def coin(bot, update):
options = ['heads (cara)', 'tails (coroa)']
c = randint(0,1)
update.message.reply_text("Coin flipped!\nCame out {}".format(options[c]))
return ConversationHandler.END
def dice(bot, update):
f = randint(1,6)
update.message.reply_text("Dice rolled!\nCame out {}".format(str(f)))
return ConversationHandler.END
def cdice(bot, update):
update.message.reply_text("Please send me a number")
return GET_CDICE
def cdice_response(bot, update):
number = update.message.text
number = number.strip()
try:
number = int(number)
f = randint(1,number)
update.message.reply_text("Dice rolled!\nCame out {}".format(str(f)))
except:
update.message.reply_text("That's not a valid number!! Please send me a number, in the numeric form! Hoowyyy!")
return GET_CDICE
return ConversationHandler.END
def error(bot, update, error):
print('Update "{}" caused error "{}"'.format(update, error))
return ConversationHandler.END
def main():
api_key = "INSERT HERE YOUR OWN"
updater = Updater(api_key)
dp = updater.dispatcher
# Commands for the bot
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start))
dp.add_handler(CommandHandler("coin", coin))
dp.add_handler(CommandHandler("dice", dice))
cdice_handler = ConversationHandler(
entry_points=[CommandHandler('cdice', cdice)],
states={
GET_CDICE: [MessageHandler(Filters.text, cdice_response)],
},
fallbacks=[MessageHandler(Filters.text,
cdice_response,
pass_user_data=True),
]
)
dp.add_handler(cdice_handler)
conv_handler = ConversationHandler(
entry_points=[CommandHandler('song', asksong)],
states={
GET_DOWNLOADMUSIC1: [MessageHandler(Filters.text, downloadmusic, pass_user_data=True)],
GET_DOWNLOADMUSIC2: [MessageHandler(Filters.text, downloadmusic_response, pass_user_data=True)],
},
fallbacks=[MessageHandler(Filters.text,
error,
pass_user_data=True),
]
)
dp.add_handler(conv_handler)
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()