def add_contact(message): """Add a new Whatsapp contact to the database. Message has the following format: /add <name> <phone> Args: message: Received Telegram message. """ if message.chat.id != SETTINGS['owner']: tgbot.reply_to(message, 'You are not the owner of this bot') return # Get name and phone args = telebot.util.extract_arguments(message.text) name, phone = args.split(maxsplit=1) if not name or not phone: tgbot.reply_to(message, 'Syntax: /add <name> <phone>') return # Check if it already exists if get_contact(phone) or get_phone(name): tgbot.reply_to(message, 'A contact with those details already exists') return # Add to database db_add_contact(name, phone) tgbot.reply_to(message, 'Contact added')
def to_tg_handler(sender, **kwargs): """Handle signals sent to Telegram. This will involve sending messages through the Telegram bot. Args: phone (str): Phone number that sent the message. message (str): The message received """ phone = kwargs.get('phone') message = kwargs.get('message', '') # Check if known contact contact = get_contact(phone) if not contact: # Unknown sender output = 'Message from #unknown\n' output += 'Phone number: %s\n' % phone logger.info('received message from unknown number: %s' % phone) else: # Known sender output = 'Message from #%s\n' % contact logger.info('received message from %s' % contact) output += '---------\n' output += message # Deliver message through Telegram for chunk in tgutil.split_string(output, 3000): tgbot.send_message(SETTINGS['owner'], chunk)
def on_message(self, message): """Received a message.""" # Parse information sender = message.getFrom(full=False) oidtotg = message.getFrom(full=True) logger.debug('received message from %s' % oidtotg) # Send receipt receipt = OutgoingReceiptProtocolEntity(message.getId(), message.getFrom(), 'read', message.getParticipant()) self.toLower(receipt) # https://github.com/tgalal/yowsup/issues/1411#issuecomment-203419530 # if isinstance(type(message), unicode) : # message = message.encode('utf-8') # entity = TextMessageProtocolEntity(message, sender) # self.toLower(entity) # Do stuff if is_blacklisted(sender): logger.debug('phone is blacklisted: %s' % sender) return participant = message.getParticipant() if participant: participant = participant.strip("@s.whatsapp.net") else: participant = sender contact_name = get_contact(participant) # body = "<" + oidtotg + ">: " + message.getBody() # body = "NULL" if message.getType() == "text": logger.debug("is text message") body = message.getBody().decode() if body == '/getID' or body == '/link': self.send_msg(phone=sender, message="/link " + sender) HelpInstructions = "Please send the above message in the Telegram group that you would like to bridge!" self.send_msg(phone=sender, message=HelpInstructions) # self.send_msg(phone=sender, message="new registrations are closed. please contact https://youtu.be/9r-yzKfL8xw for bridging Telegram ") return elif body[0:5] == '/add ': if participant == sender: name = body[5:] if not name: ReplyMessage = "Syntax: /add <name>" else: if contact_name: db_rm_contact(contact_name) db_add_contact(name, sender) ReplyMessage = "name already existed. name removed and added. Pleae verify with ```/me```" else: db_add_contact(name, sender) ReplyMessage = "name added. Pleae verify with ```/me```" self.send_msg(phone=sender, message=ReplyMessage) return elif body == '/me': if not contact_name: ReplyMessage = "Please send ```/add NAME``` to add you to my contacts." else: ReplyMessage = "I have saved your name as " + contact_name + ". You can edit your name in my contacts by sending ```/add NAME```!" if participant == sender: self.send_msg(phone=sender, message=ReplyMessage) return elif body == '/bridgeOn': toggle = db_toggle_bridge_by_wa(sender, True) if toggle is None: Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.' else: Message = 'Bridge has been turned on!' self.send_msg(phone=sender, message=Message) return elif body == '/bridgeOff': toggle = db_toggle_bridge_by_wa(sender, False) if toggle is None: Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.' else: Message = 'Bridge has been turned off. Use ```/bridgeOn``` to turn it back on.' self.send_msg(phone=sender, message=Message) return if not db_is_bridge_enabled_by_wa(sender): return logger.info("prefix WHO send this message, to message") if contact_name: TheRealMessageToSend = "<#" + contact_name + ">: " + body else: TheRealMessageToSend = "<" + participant + ">: " + body # Relay to Telegram logger.info('relaying message to Telegram') SIGNAL_TG.send('wabot', phone=sender, message=TheRealMessageToSend, media=False) if message.getType() == "media": if not os.path.exists("./DOWNLOADS"): os.makedirs("./DOWNLOADS") # set unique filename uniqueFilename = "./DOWNLOADS/%s-%s%s" % (hashlib.md5( str(message.getFrom(False)).encode('utf-8')).hexdigest(), uuid.uuid4().hex, message.getExtension()) if message.getMediaType() == "image": logger.info("Echoing image %s to %s" % (message.url, message.getFrom(False))) data = message.getMediaContent() f = open(uniqueFilename, 'wb') f.write(data) f.close() # https://github.com/AragurDEV/yowsup/pull/37 elif message.getMediaType() == "video": logger.info("Echoing video %s to %s" % (message.url, message.getFrom(False))) data = message.getMediaContent() f = open(uniqueFilename, 'wb') f.write(data) f.close() elif message.getMediaType() == "audio": logger.info("Echoing audio %s to %s" % (message.url, message.getFrom(False))) data = message.getMediaContent() f = open(uniqueFilename, 'wb') f.write(data) f.close() elif message.getMediaType() == "document": logger.info("Echoing document %s to %s" % (message.url, message.getFrom(False))) data = message.getMediaContent() f = open(uniqueFilename, 'wb') f.write(data) f.close() elif message.getMediaType() == "location": logger.info("Echoing location (%s, %s) to %s" % (message.getLatitude(), message.getLongitude(), message.getFrom(False))) uniqueFilename = "LOCATION=|=|=" + message.getLatitude( ) + "=|=|=" + message.getLongitude() elif message.getMediaType() == "vcard": logger.info("Echoing vcard (%s, %s) to %s" % (message.getName(), message.getCardData(), message.getFrom(False))) uniqueFilename = "VCARDCONTACT=|=|=" + message.getName( ) + "=|=|=" + message.getCardData() if contact_name: TheRealMessageToSend = contact_name + "=|=|=" + uniqueFilename else: TheRealMessageToSend = participant + "=|=|=" + uniqueFilename # Relay to Telegram logger.info('relaying message to Telegram') SIGNAL_TG.send('wabot', phone=sender, message=TheRealMessageToSend, media=True)
def to_tg_handler(sender, **kwargs): """Handle signals sent to Telegram. This will involve sending messages through the Telegram bot. Args: phone (str): Phone number that sent the message. message (str): The message received media (boolean): True or False """ phone = kwargs.get('phone') message = kwargs.get('message') media = kwargs.get('media') # Check if known contact contact = get_contact(phone) chat_id = SETTINGS['owner'] if media: participant_id, message_url = message.split("=|=|=") # Media Messages if not contact: output = 'Media from #unknown\n' output += 'Phone number: %s\n' % phone output += 'Participant ID: %s\n' % participant_id else: group = db_get_group(contact) if not group: output = 'Media from #%s\n' % contact output += 'Participant ID: %s\n' % participant_id else: # Contact is bound to group chat_id = group output = "Media from %s\n" % participant_id if message_url.startswith("LOCATION=|=|="): locstr, lat, lng = message_url.split("=|=|=") tgbot.send_message(chat_id, output) tgbot.send_location(chat_id, lat, lng) # vcard can be handled in a similar manner elif message_url.startswith("VCARDCONTACT=|=|="): constr, name, cdata = message_url.split("=|=|=") # TODO: but How? else: mime = magic.Magic(mime=True) mime_type = mime.from_file(message_url) if "image" in mime_type: tgbot.send_photo(chat_id, open(message_url, 'rb'), caption=output) elif "video" in mime_type: tgbot.send_video(chat_id, open(message_url, "rb"), caption=output, supports_streaming=True) else: tgbot.send_document(chat_id, open(message_url, 'rb'), caption=output) os.remove(message_url) else: # Text Messages if not contact: # Unknown sender output = 'Message from #unknown\n' output += 'Phone number: %s\n' % phone output += '---------\n' output += message logger.info('received message from unknown number: %s' % phone) else: group = db_get_group(contact) if not group: # Known sender output = 'Message from #%s\n' % contact output += '---------\n' output += message else: # Contact is bound to group chat_id = group output = message logger.info('received message from %s' % contact) # Deliver message through Telegram for chunk in tgutil.split_string(output, 3000): tgbot.send_message(chat_id, chunk)
def to_tg_handler(sender, **kwargs): """Handle signals sent to Telegram. This will involve sending messages through the Telegram bot. Args: phone (str): Phone number that sent the message. message (str): The message received media (boolean): True or False """ phone = kwargs.get('phone') message = kwargs.get('message') media: DataMedia = kwargs.get('media') # Check if known contact contact = get_contact(phone) chat_id = db_get_group(contact) if not chat_id: chat_id = SETTINGS['owner'] if media: # Media Messages type: str = media.get_type() path: str = media.get_args()[0] caption: str = media.get_kwargs()['caption'] caption = replace_phone_with_name(caption) if type == "image": tgbot.bot.send_photo(chat_id, open(path, 'rb'), caption=caption) elif type == "video": tgbot.bot.send_video(chat_id, open(path, "rb"), caption=caption, supports_streaming=True) else: tgbot.bot.send_document(chat_id, open(path, 'rb'), caption=caption) else: message = replace_phone_with_name(message) # Text Messages if not contact: # Unknown sender output = 'Message from #unknown\n' output += 'Phone number: %s\n' % phone output += '---------\n' output += message logger.info('received message from unknown number: %s' % phone) else: group = db_get_group(contact) if not group: # Known sender output = 'Message from #%s\n' % contact output += '---------\n' output += message else: # Contact is bound to group chat_id = group output = message logger.info('received message from %s' % contact) # Deliver message through Telegram for chunk in split_string(output, 3000): tgbot.bot.send_message(chat_id, chunk)
def on_message(self, message): """Received a message.""" # Parse information sender = message.getFrom(full=False) oidtotg = message.getFrom(full=True) logger.debug('received message from %s' % oidtotg) # Send receipt receipt = OutgoingReceiptProtocolEntity(message.getId(), message.getFrom(), 'read', message.getParticipant()) self.toLower(receipt) # https://github.com/tgalal/yowsup/issues/1411#issuecomment-203419530 # if isinstance(type(message), unicode) : # message = message.encode('utf-8') # entity = TextMessageProtocolEntity(message, sender) # self.toLower(entity) # Do stuff if is_blacklisted(sender): logger.debug('phone is blacklisted: %s' % sender) return participant = message.getParticipant() if participant: participant = participant.strip("@s.whatsapp.net") else: participant = sender contact_name = get_contact(participant) # body = "<" + oidtotg + ">: " + message.getBody() # body = "NULL" if message.getType() == "text": logger.debug("is text message") if (isinstance(message, TextMessageProtocolEntity)): body = message.conversation else: body = message.text if body == '/getID' or body == '/link': self.send_msg(phone=sender, message="/link " + sender) HelpInstructions = "Please send the above message in the Telegram group that you would like to bridge!" self.send_msg(phone=sender, message=HelpInstructions) # self.send_msg(phone=sender, message="new registrations are closed. please contact https://youtu.be/9r-yzKfL8xw for bridging Telegram ") return elif body[0:5] == '/add ': if participant == sender: name = body[5:] if not name: ReplyMessage = "Syntax: /add <name>" else: if contact_name: db_rm_contact(contact_name) db_add_contact(name, sender) ReplyMessage = "name already existed. name removed and added. Pleae verify with ```/me```" else: db_add_contact(name, sender) ReplyMessage = "name added. Pleae verify with ```/me```" self.send_msg(phone=sender, message=ReplyMessage) return elif body == '/me': if not contact_name: ReplyMessage = "Please send ```/add NAME``` to add you to my contacts." else: ReplyMessage = "I have saved your name as " + contact_name + ". You can edit your name in my contacts by sending ```/add NAME```!" if participant == sender: self.send_msg(phone=sender, message=ReplyMessage) return elif body == '/bridgeOn': toggle = db_toggle_bridge_by_wa(sender, True) if toggle is None: Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.' else: Message = 'Bridge has been turned on!' self.send_msg(phone=sender, message=Message) return elif body == '/bridgeOff': toggle = db_toggle_bridge_by_wa(sender, False) if toggle is None: Message = 'This group is not bridged to anywhere. Use ```/link``` to start bridging.' else: Message = 'Bridge has been turned off. Use ```/bridgeOn``` to turn it back on.' self.send_msg(phone=sender, message=Message) return if not db_is_bridge_enabled_by_wa(sender): return logger.info("prefix WHO send this message, to message") if contact_name: TheRealMessageToSend = "<#" + contact_name + ">: " + body else: TheRealMessageToSend = "<" + participant + ">: " + body # Relay to Telegram logger.info('relaying message to Telegram') SIGNAL_TG.send('wabot', phone=sender, message=TheRealMessageToSend, media=False) if message.getType() == "media": pass """