Skip to content

Instantly share code, notes, and snippets.

@spookyahell
Last active January 7, 2019 22:56
Show Gist options
  • Save spookyahell/c1b009e7b12c88e5a5b9fb55e76baa07 to your computer and use it in GitHub Desktop.
Save spookyahell/c1b009e7b12c88e5a5b9fb55e76baa07 to your computer and use it in GitHub Desktop.
Telegram bot for interacting with transfer.sh
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import CommandHandler, Updater, CallbackQueryHandler, Filters, MessageHandler
import os
import json
import logging
import requests
import re
from urllib.parse import unquote
'''Transfer.shBot operating on Telegram: @transfersh2bot
'''
logging.basicConfig(handlers = [logging.FileHandler('tfshbot.log', 'w', 'utf-8')], format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
updater = Updater(token='')
dispatcher = updater.dispatcher
def saveuserdata():
STD = open('USRDATA.json', 'w')
STD.write(json.dumps(user_data))
STD.close()
return True
if os.path.isfile('USRDATA.json'):
STD = open('USRDATA.json')
user_data = json.loads(STD.read())
else:
print('Warning: No USER DATA file to read!')
user_data = {}
def AskDoYouThinkDonaldTrumpIsAGoodPerson(bot, update):
global user_data
update.message.reply_text('I believe Donald Trump is a bad person.', reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('True', callback_data = 'Iagree')],[InlineKeyboardButton('False', callback_data = 'disagree')]]))
def CBQhandler(bot, update):
global user_data
query = update.callback_query
if query:
if query.data == 'Iagree':
user_data[str(query.from_user.id)] = {}
user_data[str(query.from_user.id)]['agreed'] = True
query.message.edit_text('Well then... Welcome abord. /start again for quick help, because that\'s all you need here!')
saveuserdata()
else:
query.message.edit_text('Well then... Have a nice life... oh and don\'t you ever use this bot!')
dispatcher.add_handler(CallbackQueryHandler(CBQhandler))
def user_actions_allowed(id):
if str(id) in user_data:
return True
else:
return False
def denyAction(bot, userid):
update.message.reply_text(userid, 'Nope, go away please. :)')
def linkhandler(bot, update):
if update.message.text in ['https://transfer.sh','https://transfer.sh/']:
update.message.reply_text('Okay you sent me the root URL of transfer.sh, now what? :D')
else:
x = re.fullmatch('https://transfer.sh/(.+)/(.+)', update.message.text)
if x:
fcode = x.group(1)
fname = x.group(2)
fname_uq = unquote(fname)
dl_link = f'https://transfer.sh/get/{fcode}/{fname}'
r = requests.get(dl_link, stream = True)
if not 'Content-Length' in r.headers:
logging.error(r.headers)
update.message.reply_text('Oops, error occured')
CL = r.headers['Content-Length']
if int(CL) > 52428800:
update.message.reply_text('ERROR: Can\'t send files that big to Telegram')
else:
if int(CL) > 20971520:
r = requests.get(dl_link)
if r.status_code == 200:
os.makedirs(str(update.message.from_user.id), exist_ok = True)
path_expected = os.path.join(str(update.message.from_user.id), fname_uq)
with open(path_expected, 'wb') as f:
f.write(r.content)
update.message.reply_document(open(path_expected, 'rb'))
else:
update.message.reply_text(f'Oops, recieved nonOK HTTP Status {r.status_code} from transfer.sh')
else:
update.message.reply_document(dl_link, timeout = 100)
else:
update.message.reply_text('Sorry not a valid transfer.sh link...')
dispatcher.add_handler(MessageHandler(Filters.entity('url'), linkhandler))
def uploadToTransferSh(path, filename, mt):
with open(path, 'rb') as datafile:
data = datafile.read()
r = requests.put(f'https://transfer.sh/{filename}', data = data, headers = {'X_FILENAME':filename, 'Content-Type':mt})
return r.text.strip()
#~ Smaller than 20971520 can be sent via HTTP request
def dochandler(bot, update):
if user_actions_allowed(update.message.from_user.id):
doc = update.message.document
print(doc)
fn = doc.file_name
fs = doc.file_size
mt = doc.mime_type
if fs > 52428800:
update.message.reply_text('File is too large, you can only send this from the webiste or a local script')
return
os.makedirs(str(update.message.from_user.id), exist_ok = True)
path_expected = os.path.join(str(update.message.from_user.id),fn)
if os.path.isfile(path_expected):
update.message.reply_text('File already uploaded. If you want to files to be sent anyway, please specify the corresponding option.')
return
update.message.reply_text('Will now upload...')
x = doc.get_file().download(path_expected)
url = uploadToTransferSh(path_expected, fn, mt)
update.message.reply_text(url)
else:
denyAction(bot, update.message.from_user.id)
dispatcher.add_handler(MessageHandler(Filters.document, dochandler))
def texthandler(bot, update):
if update.message.text.lower() == 'hi':
print('HI BACK! :)')
dispatcher.add_handler(MessageHandler(Filters.text, texthandler))
def start(bot, update):
if not user_actions_allowed(update.message.from_user.id):
update.message.reply_text('Before using this bot, you must first certify that you do not think Donald Trump is a good person.')
AskDoYouThinkDonaldTrumpIsAGoodPerson(bot, update)
else:
update.message.reply_text('Welcome to the *transfer.sh Bot*!\nYou may now start sending and recieving files from transfer.sh (max 50 MB - both ways)', parse_mode = 'Markdown')
dispatcher.add_handler(CommandHandler('start', start))
def botsource(bot, update):
update.message.reply_text('Always nice to see people interested in the source of an app...\n[transfersh2bot source on GithubGists](https://gist.github.com/spookyahell/c1b009e7b12c88e5a5b9fb55e76baa07#file-transfershtelegrambot-py-L8)', parse_mode = 'Markdown')
dispatcher.add_handler(CommandHandler('botsource', botsource))
updater.start_polling()
updater.idle()
@spookyahell
Copy link
Author

Auto deleting feature (for privacy also) will be implemented soon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment