def run(config): conf_users = config['users'].split(',') conf_secret = config['secret'] conf_validsec = int(config['validsec']) conf_jid = config['jid'] conf_jid_pw = config['jid_pw'] # reading the credential supplied in a pipe from apache username = sys.stdin.readline().strip() password = sys.stdin.readline().strip() if password == "" and username in conf_users: # avoid spamming by allowing only one message sent at a time lockfile = os.path.basename(__file__) with functions.file_lock("/tmp/lock." + lockfile): message = functions.token_message(username, conf_secret, conf_validsec, os.getenv("URI"), os.getenv("HTTP_HOST")) if os.getenv("SKIP_XMPP"): # used for testing print(message) else: functions.send_message(conf_jid, conf_jid_pw, username, message) elif username in conf_users: if functions.verify_token(username, password, conf_secret, conf_validsec): return os.EX_OK return os.EX_NOPERM # fail by default
def action_from_list(self, lst, action, until=None, message=None): # Check if a valid action is being used if action not in ["follow", "unfollow", "message", "block"]: print( "Please, use an action such as follow, unfollow, message or block" ) else: wd = self.webdriver # Get the data to use from an Excel list if type(lst) != list: user_list = get_users_from_xlsx_list(lst) else: user_list = lst # Get into Instagram account self.connection() # Action for each line for user in user_list[0:until]: wd.get('https://www.instagram.com/' + str(user) + '/') wd.implicitly_wait(10) if action == "follow": follow_from_profile(wd, user) elif action == "unfollow": unfollow_from_profile(wd, user) elif action == "message": send_message(wd, user, message) elif action == "block": block(wd, user) else: print("Invalid action") wd.quit()
def send_welcome(user): user.drop_action() send_message( user, 'Вы пролили кофе на своем рабочем месте. На что попал напиток?', keyboard=['Клавиатура', 'Сист. блок', 'Удлинитель'], action='input_deviceName')
def chatroom(request): print "CHAT PLS" input_dict = json.loads(request.body) print input_dict phone = input_dict["phone"] message = input_dict["message"] functions.send_message(phone,message) return HttpResponse("Success")
def get_biography(chat_id, user_id, message_id): biography = instagram_api.get_user_biography( username=bot_functions.get_last_username(user_id)) bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=urllib.parse.quote_plus(biography) + bot_functions.bot_address_caption, parse_mode='HTML', reply_to_message_id=message_id)
def broadcast_message(self, message): """ Sends a message to all peers :param message: The message to send :type message: Message :rtype: None """ with self.peer_lock: for peer_id in self.peers: peer_id = peer_id.split(':') send_message(message, peer_id[0], int(peer_id[1]))
def ping_handler(self, message): """ Handles a PING message. Responds with an ALIVE message. :param message: The received message. :type message: Message :rtype: None """ dst_host = message.data[0] dst_port = message.data[1] m = Message(1, 'ALIVE', [self.server_host, self.server_port]) send_message(m, dst_host, dst_port)
def start_command_handler(chat_id, user_id, first_name, last_name, username): bot_functions.send_chat_action(chat_id=chat_id, action='typing') query = "select * from users WHERE user_id={}".format(user_id) db_config.cursor.execute(query) result = db_config.cursor.fetchall() row_number = len(result) if row_number == 0: query = "INSERT INTO users(user_id,first_name,last_name,username,step) VALUES (%s, %s, %s, %s, %s)" val = (user_id, first_name, last_name, username, 'home') db_config.cursor.execute(query, val) db_config.cnx.commit() bot_functions.send_message(chat_id=chat_id, msg=messages.welcome_msg, parse_mode='HTML')
def post_message(): now = datetime.datetime.now() full_message = f'{now.hour}:{now.minute}:{now.second} - {request.form["message"]}' res = send_message(data=full_message, action=request.form['action'], vm_name=request.form['vm_name'], namespace=request.form['namespace']) flash(res) return redirect(url_for('message'))
def get_user_post_info(callback_query_id, chat_id, media_id): response = instagram_api.get_user_posts_info(media_id) if response is not None: if response == '400': bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.page_is_private + bot_functions.bot_address_caption, parse_mode='HTML') elif response == '403': bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.bot_not_work + bot_functions.bot_address_caption, parse_mode='HTML') else: text = '' post = response['items'][0] like_count = post['like_count'] comment_count = post['comment_count'] post_sender = post['user']['username'] media_type = post['media_type'] created_at = post['taken_at'] created_at = jdatetime.datetime.utcfromtimestamp( created_at).strftime('%H:%M:%S - %Y/%m/%d') if media_type == 1 or media_type == 8: text = '''\U0001F5E3 فرستنده پست: {}\n\U0001F5E3 تعداد لایک: {:,}\n\U0001F5E3 تعداد کامنت: {:,}\n\U0001F5E3 زمان ارسال پست: {}'''.format( post_sender, like_count, comment_count, created_at) elif media_type == 2: view_count = post['view_count'] text = '''\U0001F5E3 فرستنده پست: {}\n\U0001F5E3 تعداد لایک: {:,}\n\U0001F5E3 تعداد کامنت: {:,}\n\U0001F5E3 تعداد بیننده: {:,}\n\U0001F5E3 زمان ارسال پست: {} '''.format(post_sender, like_count, comment_count, view_count, created_at) bot_functions.answer_callback_query(query_id=callback_query_id, text=text, show_alert=True)
def send_message(): logger.info("[%s] - %s" % (request.method, request.path)) req = request.get_json() logger.debug(req) res = functions.send_message(req) if res != -1: logger.info('added mid=%s', res) msg = 'success' else: msg = 'error' return Response(json.dumps({'status': msg}))
def see_more_caption(chat_id, reply_to_message_id, media_id): response = instagram_api.get_user_posts_info(media_id) bot_functions.send_chat_action(chat_id=chat_id, action='typing') if response is not None: if response == '400': bot_functions.send_message(chat_id=chat_id, msg=messages.page_is_private + bot_functions.bot_address_caption, parse_mode='HTML') elif response == '403': bot_functions.send_message(chat_id=chat_id, msg=messages.bot_not_work + bot_functions.bot_address_caption, parse_mode='HTML') else: post_caption = response['items'][0]['caption']['text'] bot_functions.send_message( chat_id=chat_id, msg=urllib.parse.quote_plus(post_caption) + bot_functions.bot_address_caption, parse_mode='HTML', reply_to_message_id=reply_to_message_id)
def show_more_user_posts(chat_id, user_id, next_max_id): response = instagram_api.show_more_post(user_id, next_max_id) if response is not None: if response == '400': bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.page_is_private + bot_functions.bot_address_caption, parse_mode='HTML') elif response == '403': bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.bot_not_work + bot_functions.bot_address_caption, parse_mode='HTML') else: parse_user_posts_response(chat_id, response) else: bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.no_exist_post + bot_functions.bot_address_caption, parse_mode='HTML')
def hello_handler(self, message): """ Handles a HELLO message. Adds the peer to the peer list if enough room. Sends it back our peer list. :param message: The received message. :type message: Message :rtype: None """ new_host = message.data[0] new_port = int(message.data[1]) if self.max_peers_reached(): sorted_peers = self.get_sorted_peers() if sorted_peers is not None: first_peer = sorted_peers[0] self.remove_peer(first_peer['host'], first_peer['port']) self.add_peer(new_host, new_port) with self.peer_lock: m = Message(1, 'PEERS', list(self.peers.keys())) send_message(m, new_host, new_port)
def username_command_handler(chat_id, user_id, text): if '@' in str(text): at_sign_char_index = str(text).index('@') if at_sign_char_index == 0: text = text[1:] if 'https://instagram.com/' in str(text): url_char_index = str(text).index('https://instagram.com/') if url_char_index == 0: text = text[22:] bot_functions.set_last_username(user_id, text) username_info = instagram_api.get_username_info(text) if username_info is not None: if username_info == '404': # 404 mean : user not found bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.user_not_found + bot_functions.bot_address_caption, parse_mode='HTML') elif username_info == '401': # 401 mean : wrong input bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.wrong_input + bot_functions.bot_address_caption, parse_mode='HTML') elif username_info == '403': # 403 mean : login required (the problem is ours : cookies is expired) bot_functions.send_chat_action(chat_id=chat_id, action='typing') bot_functions.send_message(chat_id=chat_id, msg=messages.bot_not_work + bot_functions.bot_address_caption, parse_mode='HTML') else: full_name = username_info['full_name'] username = username_info['username'] media_count = username_info['media_count'] follower_count = username_info['follower_count'] following_count = username_info['following_count'] is_private = username_info['is_private'] if is_private: page_status = 'قفل (Private)' else: page_status = 'باز (Public)' biography = username_info['biography'] external_url = username_info['external_url'] caption = '''\U0001F5E3 <b>نام نمایشی: </b>{} \U0001F464 <b>نام کاربری: </b>{} \U0001F4E5 <b>تعداد پست: </b>{:,} \N{leftwards black arrow} <b>تعداد فالوور: </b>{:,} \N{black rightwards arrow} <b>تعداد فالووینگ: </b>{:,} \N{lock} <b>وضعیت صفحه: </b>{} \U0001F4DC <b>بیوگرافی:</b> {} \U0001F517 <b>لینک:</b> <a href='{}'>{}</a> '''.format(full_name, username, media_count, follower_count, following_count, page_status, urllib.parse.quote_plus(biography), external_url, external_url) + bot_functions.bot_address_caption markup = { 'inline_keyboard': [[{ 'text': '\U0001F4E5 ' + 'بیوگرافی', 'callback_data': 'get_biography' }, { 'text': '\U0001F4E5 ' + 'پروفایل', 'callback_data': 'get_profile' }], [{ 'text': '\U0001F4E5 ' + 'هایلایت ها', 'callback_data': 'get_highlights' }, { 'text': '\U0001F4E5 ' + 'استوری ها', 'callback_data': 'get_stories' }, { 'text': '\U0001F4E5 ' + 'پست ها', 'callback_data': 'get_posts' }], [{ 'text': '\U0001F4E5 ' + 'مشاهده صفحه در اینستاگرام', 'url': 'https://instagram.com/{}'.format(text) }]] } bot_functions.send_chat_action(chat_id=chat_id, action='upload_photo') response = bot_functions.send_photo( chat_id=chat_id, photo_link=username_info['hd_profile_pic_url_info']['url'], caption=caption, parse_mode='HTML', markup=json.dumps(markup)) message_id = response['result']['message_id'] bot_functions.set_last_message_id(user_id, message_id)
import sys from functions import get_covid_today, send_message if __name__ == "__main__": status, message = get_covid_today() if status: username = sys.argv[1] send_message(username, message)
if peer_port != port_number: peer.add_peer(ip, peer_port) name = ip + ':' + str(port_number) t = threading.Thread(target=peer.mainloop, name=name) t.start() # time.sleep(0.5) for peer in peers: peer.debug = True print('CREATED ALL PEERS') time.sleep(4) print('STARTING ANOTHER PEER') time.sleep(1) port_number = 1566 peer = PeerNode(max_peers, port_number) print('Creating peer ', port_number) peer.add_peer(ip, 4567) peer.add_peer(ip, 4568) peers.append(peer) name = ip + ':' + str(port_number) t = threading.Thread(target=peer.mainloop, name=name) t.start() m = Message(10, 'GET', ['http://pcksr.net/ptir.php?legit']) send_message(m, 'localhost', 1566)
def send_token(conf, username, orig_uri): message = functions.token_message(username, conf.secret, conf.validsec, orig_uri) if conf.skip_xmpp: # used for testing print(message) else: functions.send_message(conf.jid, conf.password, username, message)
from functions import send_message if __name__ == "__main__": send_message("Ice", "Hello World")
def handle_message(user: User, message: str): if message in ['/start', 'Домой']: send_welcome(user) return True if user.action: action = user.action user.drop_action() if action.find('input_') == 0: key = action.split('_')[1] if key == 'deviceName': if message == 'Клавиатура': send_message(user, 'На клавиатуру от компьютера?', keyboard=['Да', 'Нет'], action='input_submitKeyboardType') return True elif message == 'Сист. блок': send_message(user, """Следуй этой инструкции 1) Убери следы кофе с корпуса 2) Полностью отключи компьютер для твоей безопасности 3) Разбери компьютер и посмотри, куда именно попал напиток Самым оптимальным вариантом для тебя является обратиться к куратору и объяснить ситуацию. Ты уже обратился к своему наставнику?""", keyboard=['Да', 'Нет'], action='input_submitHeadConnect') return True elif message == 'Удлинитель': send_message( user, """Следуй этой инструкции 1) Выключи удлинитель из розетки 2) Вызови мастера электрика, чтобы безопасно исправить полученную проблему В случае серьезных проблем, звонить 101""") send_welcome(user) return True elif key == 'submitKeyboardType': if message in ['Да', 'Нет']: send_message( user, 'Вы протерли стол и кнопки клавиатуры (вынули, почистили, высушили, засунули). Исправно ли работает устройство?', keyboard=['Да', 'Нет'], action='input_submitDeviceOnline') return True elif key == 'submitDeviceOnline': if message == 'Да': send_message(user, 'Отлично! Советую так больше не делать') send_welcome(user) return True elif message == 'Нет': send_message(user, """Следуйте следующей инструкции: 1) Выключи клавиатуру, отключив провод 2) Переверни устройство и отверткой открути нижнюю крышку. Винтики не теряй. Сними крышку 3) Аккуратно достань мембану и протри сухой чистой тряпочкой электропроводящую пленку 4) Собери все обратно. Окончательно просуши. Запомни, все внутренности должны быть сухими, дай им время обсохнуть 5) Подожди несколько минут и попробуй включить устройство Клавиатура заработала?""", keyboard=['Да', 'Нет'], action='input_submitKeyboardFix1') return True elif key == 'submitKeyboardFix1': if message == 'Да': send_message( user, 'Отлично! Постарайся больше такого не допускать') send_welcome(user) return True elif message == 'Нет': send_message( user, 'В таком случае остается только один выход - сдать устройство в сервис, телефон +74992223322' ) send_welcome(user) return True elif key == 'submitHeadConnect': if message == 'Да': send_message( user, 'Ты правильно поступил, но в следующий раз лучше до такого не доводить' ) send_welcome(user) return True elif message == 'Нет': send_message( user, 'Срочно обратись к своему куратору, чтобы он мог тебе помочь' ) send_welcome(user) return True send_message( user, 'Пользуйтесь только встроенной клавиатурой, Вы возвращены в начало') send_welcome(user) return True