def random(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/random number`') return if context.args[0] == 'number': if len(context.args) == 1: context.bot.send_message(chat_id=update.message.chat_id, text=f'{randint(1, 100)}') elif len(context.args) == 3: try: context.bot.send_message( chat_id=update.message.chat_id, text= f'{randint(int(context.args[1]), int(context.args[2]))}') except ValueError: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/random number [range_start] [range_end]`') else: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/random number [range_start] [range_end]`')
def send_tweet(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/tweet <your tweet>`') return # join the list of words into a single string tweet_text = ' '.join(context.args) if len(tweet_text) > 280: context.bot.send_message(chat_id=update.message.chat_id, text='Can\'t send tweet, because it is longer than 280 characters') return auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) tweet = api.update_status(status=tweet_text) context.bot.send_message(chat_id=update.message.chat_id, text=f'Tweet send: https://twitter.com/user/status/{tweet.id}')
def set_group_avatar(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not update['message']['reply_to_message'] or not update['message'][ 'reply_to_message']['photo']: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/setpic (as a reply to an image)`') return photo_update = update['message']['reply_to_message']['photo'][-1] profile_pic = context.bot.get_file(file_id=photo_update['file_id']) profile_pic.download('avatar.jpg') with open('avatar.jpg', 'rb') as file: try: context.bot.set_chat_photo(update.message.chat_id, file) except BadRequest: context.bot.send_message( chat_id=update.message.chat_id, text= 'Either I don\'t have permission to change the avatar, or we\'re not currently chatting in a group.' ) os.remove('avatar.jpg')
def rate(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/rate [thing]`') else: ratings = [ ', I\'d say that this horribly sucks and gets what it deserves : a 0/10.', ', I\'d say that this horribly sucks and gets what it deserves : a 1/10.', ', I\'d say that this is bad and only deserves a 2/10.', ', I\'d say that this is bad and only deserves a 3/10.', ', I\'d say that this is quite average and can be rated something like 4/10.', ', I\'d say that this is quite average and can be rated something like 5/10.', ', I\'d say that this is quite good and should get a 6/10.', ', I\'d say that this is quite good and should get a 7/10.', ', I\'d say that this is (relatively) incredible and deserves a 8/10.', ', I\'d say that this is (relatively) incredible and deserves a 9/10.', ', I\'d say that this is incredibly awesome and should get the perfect score : 10/10.' ] random.seed( hashlib.md5(''.join( context.args).lower().encode('utf-8')).hexdigest()) rating = ratings[random.randint(0, 10)] context.bot.send_message( chat_id=update.message.chat_id, text=f'{update.message.from_user.username}{rating}')
def send_media_from_url(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return # file extentions it will look for image_extensions = {'.png', '.jpg'} document_extensions = {'.gif', '.pdf', '.zip'} video_extensions = {'.mp4', '.mov'} msgent = update['message']['entities'][0] msgoffset = msgent['offset'] msglength = msgent['length'] # gets the url out of the message even if the message contains other text too url = update['message']['text'] url = url[int(msgoffset):] url = url[:int(msglength)] # checks for Instagram post and send the full res image if 'https://www.instagram.com/p/' in url: context.bot.send_chat_action(update.message.chat_id, ChatAction.UPLOAD_PHOTO) context.bot.send_photo(chat_id=update.message.chat_id, photo=url) # checks every received URL if it is a direct link to a file, and returns the file itself if it is if posixpath.splitext( urllib.parse.urlparse(url).path)[1] in image_extensions: context.bot.send_chat_action(update.message.chat_id, ChatAction.UPLOAD_PHOTO) try: urllib.request.urlretrieve(url, 'downloaded_photo.jpg') with open('downloaded_photo.jpg', 'rb') as downloaded_photo: files = {'photo': downloaded_photo} params = {'chat_id': update.message.chat_id} api_url = f'https://api.telegram.org/bot{api_key}/sendPhoto' requests.post(api_url, files=files, params=params) os.remove('downloaded_photo.jpg') except BadRequest: context.bot.send_photo(chat_id=update.message.chat_id, photo=url) elif posixpath.splitext( urllib.parse.urlparse(url).path)[1] in document_extensions: context.bot.send_chat_action(update.message.chat_id, ChatAction.UPLOAD_DOCUMENT) context.bot.send_document(chat_id=update.message.chat_id, document=url) elif posixpath.splitext( urllib.parse.urlparse(url).path)[1] in video_extensions: context.bot.send_chat_action(update.message.chat_id, ChatAction.UPLOAD_VIDEO) try: urllib.request.urlretrieve(url, 'downloaded_video.mp4') with open('downloaded_video.mp4', 'rb') as downloaded_video: files = {'video': downloaded_video} params = {'chat_id': update.message.chat_id} api_url = f'https://api.telegram.org/bot{api_key}/sendVideo' requests.post(api_url, files=files, params=params) os.remove('downloaded_video.mp4') except BadRequest: context.bot.send_video(chat_id=update.message.chat_id, video=url)
def filter_commands(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/filter add <word> | remove <word> | list`') return # function that adds or removes words from the db, 1 == add, 0 == remove. def add_remove(words, add): if len(words) < 1: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/filter add <word> | remove <word> | list`') return if add: sql = 'INSERT OR IGNORE INTO wordfilter (chatid, word) VALUES (?, ?)' success = 'Your words were added to the filter.' else: sql = 'DELETE FROM wordfilter WHERE chatid = ? AND word = ?' success = 'Your words were removed from the filter.' data = [] for word in words: data.append((update.message.chat_id, word)) c.executemany(sql, data) conn.commit() context.bot.send_message(chat_id=update.message.chat_id, text=success) if context.args[0] == 'add': add_remove(context.args[1:], 1) if context.args[0] == 'remove': add_remove(context.args[1:], 0) if context.args[0] == 'list': c.execute('SELECT word FROM wordfilter WHERE chatid = ?', [update.message.chat_id]) result = ', '.join(c.fetchall()) if not result: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text= 'This chat doesn\'t have any filtered words, add one using `/filter add <word>`' ) else: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text=f'{result}') return
def wheeldecide(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if len(context.args) < 2: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/wheeldecide <option 1> <option 2>`') else: context.bot.send_message(chat_id=update.message.chat_id, text=context.args[random.randint(0, len(context.args) - 1)])
def update(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return updatecommand = 'git pull' output = os.popen(updatecommand).read() context.bot.send_message(chat_id=update.message.chat_id, text=output) if output.strip() != 'Already up-to-date.': os.execl(sys.executable, sys.executable, *sys.argv)
def dogify(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/dogify <your words>`') else: all_words = ' '.join(context.args) context.bot.send_photo(chat_id=update.message.chat_id, photo=f'http://dogr.io/{all_words}.png?split=false&.png')
def kickme(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return try: context.bot.kick_chat_member(chat_id=update.message.chat_id, user_id=update.message.from_user['id']) except BadRequest: context.bot.send_message(chat_id=update.message.chat_id, text=f'Sorry, I can\'t kick you.')
def magic8ball(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful'] context.bot.send_message(chat_id=update.message.chat_id, text=answers[random.randint(0, len(answers) - 1)])
def echo(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/echo <your words>`') else: all_words = ' '.join(context.args) context.bot.send_message(chat_id=update.message.chat_id, text=all_words)
def get_id(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args or context.args[0] != 'group': context.bot.send_message( chat_id=update.message.chat_id, text=f'Your user id is: {update.message.from_user.id}') return context.bot.send_message( chat_id=update.message.chat_id, text=f'This group\'s id is: {update.message.chat_id}')
def qr(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/qr <text>`') return text = ' '.join(context.args) url = f"https://api.qrserver.com/v1/create-qr-code/?data={text}&size=600x600" context.bot.send_chat_action(update.message.chat_id, ChatAction.UPLOAD_PHOTO) context.bot.send_photo(chat_id=update.message.chat_id, photo=url)
def quote(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: c.execute('SELECT quote FROM quote WHERE chatid = ?', [update.message.chat_id]) quotes = c.fetchall() if quotes: quote = quotes[random.randint(0, len(quotes) - 1)] context.bot.send_message(chat_id=update.message.chat_id, text=quote) else: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text= 'This chat doesn\'t have any quotes, add one using `/quote add <your quote>`' ) elif context.args[0] == 'add' and len(context.args) > 1: try: data = [ update.message.chat_id, ' '.join(context.args[1:]), update.message.from_user.id ] c.execute( 'INSERT INTO quote (chatid, quote, user) VALUES (?, ?, ?)', data) conn.commit() except sqlite3.IntegrityError: context.bot.send_message(chat_id=update.message.chat_id, text='Your quote couldn\'t be added.') return context.bot.send_message(chat_id=update.message.chat_id, text=f'Your quote was added successfully.') else: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/quote [add <your quote>]`')
def search_ddg(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/google <keyword(s)>`') return # join the list of words into a single string with '+' between every word all_keywords = '+'.join(context.args) context.bot.send_chat_action(update.message.chat_id, ChatAction.TYPING) url = f'https://duckduckgo.com/html/?q={all_keywords}' # added user agent so we get blocked less often. it might still happen though r = requests.get( url, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' }) soup = BeautifulSoup(r.text, 'lxml') result = soup.find( class_='result results_links results_links_deep web-result') # split the title, text and url in a list result = result.text.splitlines() # filter whitespace and empty strings from list result = [r.strip() for r in result if r] try: result = f'*{result[1]}* \n{result[4]} \n\n{result[2]}' except IndexError: context.bot.send_message(chat_id=update.message.chat_id, text=f'No results found for {all_keywords}') return context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text=result, disable_web_page_preview=True)
def set_group_title(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args or len(context.args) > 254: context.bot.send_message( chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/settitle <new group title> (<255 characters)`') return title = ' '.join(context.args) try: context.bot.set_chat_title(update.message.chat_id, title=title) except BadRequest: context.bot.send_message( chat_id=update.message.chat_id, text= 'Either I don\'t have permission to change the title, or we\'re not currently chatting in a group.' )
def isup(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args or len(context.args) > 1: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/isup <url>`') return else: url = context.args[0] if 'https://' not in url and 'http://' not in url: # if no http(s) in url, add it, and check if url is up url = 'http://' + url # add http to url try: r = requests.get(url) if r.ok: context.bot.send_message(chat_id=update.message.chat_id, text=f'{url} Looks up from here!') except requests.exceptions.ConnectionError: context.bot.send_message(chat_id=update.message.chat_id, text=f'{url} Looks down from here, RIP')
def love(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if not context.args or 2 > len(context.args) > 4: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/love <name> <name>`') return else: total_rating = 0 for name in context.args: random.seed(hashlib.md5(name.lower().encode('utf-8')).hexdigest()) total_rating += random.randint(0, 50) random.seed( hashlib.md5(str(total_rating).lower().encode('utf-8')).hexdigest()) final_rating = random.randint(0, 100) text = texts[int(final_rating / 10)] context.bot.send_message(chat_id=update.message.chat_id, text=f"{final_rating}%, {text}")
def remind(update, context): new_message.new_message(update) if enable_check.enable_check(__name__): return if len(context.args) < 2: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/remind <2d1h23m> <text>`') return regex = re.fullmatch(r'(\d+[d|h|m]){1,3}', context.args[0]) # todo doesn't catch 100% of problems if not regex: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/remind <2d1h23m> <text>`') return reminddate = context.args[0] text = ' '.join(context.args[1:]) total = 0 if match := re.search('\d+[d]', reminddate): total += int(match[0][:-1]) * 86400
def crypto(update, context): new_message.new_message(update) with open('config.yaml', 'r') as f: config = yaml.full_load(f) apikey = config['CRYPTO']['API_KEY'] if enable_check.enable_check(__name__): return def changepct(time): if len(context.args) >= 2: currency1 = context.args[1] else: currency1 = "BTC" if len(context.args) == 3: currency2 = context.args[2] else: currency2 = "USD" url = f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?CMC_PRO_API_KEY={apikey}&symbol={currency1.upper()}&convert={currency2.upper()}" r = requests.get(url) msg = r.json()['data'][currency1.upper()]['quote'][ currency2.upper()][f'percent_change_{time[:-1]}'] if msg > 0.01 or msg < -0.01: msg = round(msg, 2) if msg > 0.0: msg = f"+{msg}" return msg # crypto % change for past 24h, 7d, 30d if len(context.args) >= 1 and context.args[0] in ['24h%', '7d%', '30d%']: msg = changepct(context.args[0]) context.bot.send_message(chat_id=update.message.chat_id, text=f'{msg}%') # /crypto 24h btc elif len(context.args) >= 1 and context.args[0] == "24h": if len(context.args) >= 2: currency1 = context.args[1] else: currency1 = "BTC" if len(context.args) == 3: currency2 = context.args[2] else: currency2 = "USD" try: symbol = currency.symbol(currency2, native=False) except: symbol = "" avg = cryptocompare.get_avg(currency1, currency=currency2) msg = avg['CHANGE24HOUR'] if msg > 0.01 or msg < -0.01: msg = round(msg, 2) if msg > 0.0: msg = f"+{msg}" context.bot.send_message(chat_id=update.message.chat_id, text=f"{msg}{symbol}") # /crypto btc eur elif len(context.args) >= 1: currency1 = context.args[0].upper() if len(context.args) == 2: currency2 = context.args[1].upper() else: currency2 = "USD" try: symbol = currency.symbol(currency2, native=False) except: symbol = '' price = cryptocompare.get_price(currency1, currency=currency2, full=False) if price: context.bot.send_message( chat_id=update.message.chat_id, text=f"{symbol}{price[currency1][currency2]}") else: context.bot.send_message(chat_id=update.message.chat_id, text=f"Sorry, can\'t find {currency1}") return elif not context.args or len(context.args) > 3: context.bot.send_message(chat_id=update.message.chat_id, parse_mode='markdown', text='Usage: `/crypto <btc,eth,xmr,etc>`') return