-
Notifications
You must be signed in to change notification settings - Fork 3
/
bp_telegram.py
executable file
·291 lines (255 loc) · 9.47 KB
/
bp_telegram.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env python3
# coding=utf-8
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, \
ConversationHandler, InlineQueryHandler, RegexHandler
from telegram import InlineQueryResultArticle, InputTextMessageContent, \
MessageEntity, ParseMode
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import re
from uuid import uuid4
import requests
import tempfile
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# access bot via token
updater = Updater(token='AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
dispatcher = updater.dispatcher
second = 2
# get token
def tokenize(bot, job):
global headers
try:
tokenRequest = requests.post(
'https://beepaste.io/api/v1/auth',
headers={'Content-Type': 'application/json'}, verify=False)
token_json = tokenRequest.json()
if token_json['status'] == 'success':
token = token_json['X-TOKEN']
headers = {'X-TOKEN': token}
except Exception as e:
print('\nError: ' + e)
# main function , paste to beepaste.io
def paste(text, author):
data = {
'raw': text,
'title': 'A new paste',
'author': author + ' via 🤖@BPaste_bot on Telegram '
}
try:
r = requests.post(
'https://beepaste.io/api/v1/paste',
headers=headers, json=data, verify=False)
except Exception as e:
print(e)
rj = r.json()
if rj['status'] == 'success':
rjp = rj['paste']
return rjp
else:
return False
tokenize()
# expand paste
def expand(link):
pid = link.split('/')[5].split(' ')[0]
try:
r = requests.get(
'https://beepaste.io/api/v1/paste/' + pid,
headers=headers
)
except Exception as e:
print(e)
rj = r.json()
if rj['status'] == 'success':
return rj['paste']
else:
return False
tokenize()
# expand paste in direct
def expand_direct(bot, update):
try:
p = expand(update.message.text)
res = '🔗 https://beepaste.io/paste/view/' + p['uri'] + \
'\n👤 ' + p['author'].replace('_', '\\_') + \
'\n```\n\n' + p['raw'] + '\n```'
bot.sendMessage(
chat_id=update.message.chat_id,
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_to_message_id=update.message.message_id,
text=res
)
except Exception as e:
bot.sendMessage(
chat_id=update.message.chat_id,
reply_to_message_id=update.message.message_id,
text='❌'
)
# start_handler function
def start(bot, update):
update.message.reply_text('Hi, Give me your long text or send me your file')
return second
# get file and paste
def filef(bot, update):
# get file id
file = bot.getFile(update.message.document.file_id)
# create a randon temp file name
tf = tempfile.mkstemp()
# download file
file.download(tf[1])
# read file content
try:
tfco = open(tf[1], "r")
tfc = tfco.read()
tfco.close()
except Exception as e:
# if it is not text file
bot.sendMessage(
chat_id=update.message.chat_id,
reply_to_message_id=update.message.message_id,
text=" ⚠️ Please send me a text file")
# get user name for author
try:
author = update.message.from_user.first_name + " " \
+ update.message.from_user.last_name
except Exception:
author = "Anonymous user"
# call paste function
p = paste(tfc, author)
# replay the url to user
bot.sendMessage(
chat_id=update.message.chat_id,
reply_to_message_id=update.message.message_id,
text='🔗 https://beepaste.io/paste/view/' + p['uri'] + \
'\n🔗 ' + p['shorturl']
)
def second(bot, update):
# get text
txt = update.message.text
# get user name for author
try:
author = update.message.from_user.first_name + " " + \
update.message.from_user.last_name
except Exception:
author = "Anonymous user"
# call paste function
p = paste(txt, author)
# replay the url to user
bot.sendMessage(
chat_id=update.message.chat_id,
reply_to_message_id=update.message.message_id,
text='🔗 https://beepaste.io/paste/view/' + p['uri'] + \
'\n🔗 ' + p['shorturl']
)
# cancel function
def cancel(bot, update):
bot.sendMessage(chat_id=update.message.chat_id, text="canceled")
# About function
def about(bot, update):
abouttext = "@BPaste_bot , Can Paste Long Text and File Content In Groups and Private Chats , Via inline Mode Or Directly or Expand your Paste \n🆓 This Bot , Totaly Free , Libre and OpenSource \n 🌐 https://github.com/mostafaasadi/bpastebot "
bot.sendMessage(chat_id=update.message.chat_id, text=abouttext)
# inline respond function
def inlinequery(bot, update):
query = update.inline_query.query
results = list()
# beepaste link to expand
if re.match('https://beepaste.io/paste/view\S+', query):
p = expand(query)
res = '🔗 https://beepaste.io/paste/view/' + p['uri'] + \
'\n👤 ' + p['author'].replace('_', '\\_') + \
'\n```\n\n' + p['raw'] + '\n```'
results.append(InlineQueryResultArticle(
id=uuid4(),
title=" ✅ Expanded!",
description=p['author'].replace('_', '\\_'),
url=p['shorturl'],
thumb_url="http://mostafaasadi.ir/bots/beepastelogo.png",
input_message_content=InputTextMessageContent(
res,
disable_web_page_preview=True,
parse_mode=ParseMode.MARKDOWN)))
else:
try:
author = update.inline_query.from_user.first_name + " " + \
update.inline_query.from_user.last_name
# set name for Anonymous user
except Exception:
author = "Anonymous user"
# add inline query to bot
# inline mode for zero character
if len(query) == 0:
results.clear()
results.append(InlineQueryResultArticle(
id=uuid4(),
title=" ▶️ BPaste",
description="type some text less than 256 character inline mode or a paste link to expand",
url="t.me/bpaste_bot",
thumb_url="http://mostafaasadi.ir/bots/beepastelogo.png",
input_message_content=InputTextMessageContent(
"BPaste, paste your world! \n@bpaste_bot")))
# inline mode for long text
elif len(query) > 255:
results.clear()
results.append(InlineQueryResultArticle(
id=uuid4(),
title=" Sorry! 😞",
description=" ⚠️ We can't get long long text in inline mode, send it directly",
url="t.me/bpaste_bot",
thumb_url="http://mostafaasadi.ir/bots/beepastelogo.png",
input_message_content=InputTextMessageContent(
"We can't get so long text in inline mode, send it directly, @bpaste_bot")))
# inline mode for normal text
else:
results.clear()
p = paste(query, author)
results.append(InlineQueryResultArticle(
id=uuid4(),
title=" ✅ Pasted!",
description=" pasted with this link",
url=p['shorturl'],
thumb_url="http://mostafaasadi.ir/bots/beepastelogo.png",
input_message_content=InputTextMessageContent(
'🔗 https://beepaste.io/paste/view/' + p['uri'] + \
'\n🔗 ' + p['shorturl'])))
# update inline respond
update.inline_query.answer(results)
def main():
# manage conversation
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
second: [MessageHandler(Filters.text, second)]},
fallbacks=[CommandHandler('cancel', cancel)])
# it handle start command
start_handler = CommandHandler('start', start)
# handle all text
second_handler = MessageHandler(
Filters.text | Filters.entity(MessageEntity.TEXT_LINK) &
~ Filters.entity(MessageEntity.URL),
second
)
filef_handler = MessageHandler(Filters.document, filef)
# handle cancel
cancel_handler = CommandHandler('cancel', cancel)
# handle cancel
about_handler = CommandHandler('about', about)
# handle dispatcher
dispatcher.add_handler(InlineQueryHandler(inlinequery))
dispatcher.add_handler(start_handler)
# handle beepaste link for expand
dispatcher.add_handler(
RegexHandler(
'https://beepaste.io/paste/view\S+',
expand_direct
)
)
dispatcher.add_handler(second_handler)
dispatcher.add_handler(conv_handler)
dispatcher.add_handler(cancel_handler)
dispatcher.add_handler(about_handler)
dispatcher.add_handler(filef_handler)
j = updater.job_queue
j.run_repeating(tokenize, interval=840, first=0)
# run
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()