本文整理汇总了Python中twx.botapi.TelegramBot.send_message方法的典型用法代码示例。如果您正苦于以下问题:Python TelegramBot.send_message方法的具体用法?Python TelegramBot.send_message怎么用?Python TelegramBot.send_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twx.botapi.TelegramBot
的用法示例。
在下文中一共展示了TelegramBot.send_message方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
class NotificationSender:
def __init__(self, bot_token, user_id):
self.bot = TelegramBot(bot_token)
self.user_id = user_id
def send_message(self, message):
self.bot.send_message(self.user_id, message).wait()
示例2: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def main():
print '[+] Starting bot...'
# Read the config file
print '[+] Reading config file...'
config = ConfigParser.ConfigParser()
config.read([os.path.expanduser('./config')])
# Read data
bot_name = config.get('bot', 'name')
bot_token = config.get('bot', 'token')
cool_answers_raw = config.get('phrases', 'cool_answers')
cool_answers = [ answer for answer in cool_answers_raw.split('"') if answer and answer!=',']
# Last mssg id:
last_id = int(load_last_id())
print '[+] Last id: %d' % last_id
# Configure regex
regex = re.compile('[%s]' % re.escape(string.punctuation))
# Create bot
print '[+] Connecting bot...'
bot = TelegramBot(bot_token)
bot.update_bot_info().wait()
print '\tBot connected! Bot name: %s' % bot.username
while True:
try:
updates = bot.get_updates(offset=last_id).wait()
for update in updates:
id = update.message.message_id
update_id = update.update_id
user = update.message.sender
chat_id = update.message.chat.id
text = update.message.text
if int(update_id) > last_id:
last_id = update_id
save_last_id(last_id)
save_log(id, update_id, chat_id, text)
#text = regex.sub('', text)
words = text.split()
for word in words:
# Process commands:
if 'http://' in word or 'https://' in word:
# Get a random answer phrase:
answer = random.choice(cool_answers)
bot.send_message(chat_id, answer)
except (KeyboardInterrupt, SystemExit):
print '\nkeyboardinterrupt caught (again)'
print '\n...Program Stopped Manually!'
raise
示例3: telebot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def telebot(news):
"""
This Telegram bot sends a message about stock news to a user using
TWX bot library. More about this library may be find at:
https://pythonhosted.org/twx/twx/botapi/botapi.html#module-twx.botapi
"""
bot = TelegramBot('182387487:AAGiA489MZtosNOkhLjzo3_6l7xCYkG4N5A')
bot.update_bot_info().wait()
updates = bot.get_updates().wait()
for update in updates:
user_id, = re.findall("sender=User.id=(\d+)", str(update))
if user_id not in users:
users.append(user_id)
for user in users:
user_id = int(user)
bot.send_message(user_id, news)
示例4: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def main():
last_post_date, tgm_data = load_settings()
rss = feedparser.parse(settings.RSS_URL)
logging.debug("last_post_date: %s", last_post_date.isoformat())
# find new entries in feed
new_entries = []
for entry in rss.entries:
try:
entry_published = datetime.utcfromtimestamp(
calendar.timegm(entry.published_parsed))
if entry_published > last_post_date:
new_entries.append(entry)
except AttributeError as e:
logging.error("%s\n%s", e, entry)
logging.info('The number of new entries: %s\nEntries: %s',
len(new_entries),
[(item.get('id'), item.get('published_parsed')) for item in
new_entries])
date = datetime.now()
if not new_entries:
logging.info('New entries are not found')
save_settings(date.isoformat())
return
# sort new entries by published date
new_entries.sort(key=lambda item: item.published_parsed)
# send to telegram channel
tgm_bot = TelegramBot(settings.TGM_BOT_ACCESS_TOKEN)
for entry in new_entries:
try:
logging.debug("Raw message:\n%s\n", entry.description)
text = entry.title + '\n\n' + entry.link + '\n\n' + entry.description
message = remove_tags(text)
logging.debug("message:\n%s\n", message)
except AttributeError as e:
logging.error("%s\n%s", e, entry)
continue
answer = tgm_bot.send_message(settings.TGM_CHANNEL, message).wait()
if isinstance(answer, twx.botapi.Error):
logging.error("error code: %s\nerror description: %s\n",
answer.error_code,
answer.description)
break
else:
date = max(
datetime.utcfromtimestamp(
calendar.timegm(entry.published_parsed)),
date
)
time.sleep(1)
save_settings(date.isoformat())
示例5: update
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def update():
bot = TelegramBot(token)
bot.update_bot_info().wait()
if 'chat' in request.json['message']:
chat = request.json['message']['chat']['id']
if 'text' in request.json['message']:
text = request.json['message']['text']
if text.find('vice') != -1:
bot.send_message(chat, vice()).wait()
if text.find('drink') != -1:
bot.send_photo(chat,bill()).wait()
#Print in console for fast Debugging
print(json.dumps(request.json))
return "ok"
示例6: pub_to_telegram
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def pub_to_telegram(text, bot_token, tg_channel):
tgm_bot = TelegramBot(bot_token)
answer = tgm_bot.send_message(tg_channel, text).wait()
if isinstance(answer, twx.botapi.Error):
print('error code: %s\nerror description: %s\n',
answer.error_code,
answer.description)
else:
print('OK')
示例7: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def main():
try:
with open('API_KEY', 'r') as f:
api_key = f.read().replace('\n', '')
except IOError:
print "please write the api key in file `API_KEY`"
exit(1)
bot = TelegramBot(api_key)
bot.update_bot_info().wait()
print(bot.username)
last_update_id = int(0)
last_fortune = (datetime.now() - timedelta(minutes=31))
while True:
try:
updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
for update in updates:
last_update_id = update.update_id
print(update)
process_update(bot, update)
global rems
for rem in rems:
if rem.when < datetime.now():
bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" +
unicode(rem.what))
print "removing reminder " + str(rem.id)
rems = [r for r in rems if r.id != rem.id]
print "rems = " + str(rems)
odd = random.randint(0, 100)
thirty_minutes = (datetime.now() - datetime.timedelta(minutes=5))
if last_fortune < thirty_minutes and 50 < odd:
last_fortune = datetime.datetime.now()
msg = subprocess.check_output("fortune") + ' #fortune'
bot.send_message(update.message.chat.id, msg)
except KeyboardInterrupt:
# Allow ctrl-c.
raise KeyboardInterrupt
except Exception as e:
print "---\nException: "
print e
traceback.print_exc()
pass
示例8: YoutubeBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
class YoutubeBot(object):
api_token = ''
def __init__(self):
self.bot = TelegramBot(self.api_token)
self.bot.get_me()
last_updates = self.bot.get_updates(offset=0).wait()
try:
self.last_update_id = list(last_updates)[-1].update_id
except IndexError:
self.last_update_id = None
print 'last update id: {}'.format(self.last_update_id)
def process_message(self, message):
text = message.message.text
chat = message.message.chat
text = text.strip().split('&')[0]
msg = 'Could not download {}'.format(text)
print 'Got message: \33[0;32m{}\33[0m'.format(text)
try:
self.bot.send_message(chat.id, 'Staring to download')
with youtube_dl.YoutubeDL(YDL_OPTS) as ydl:
r_code = ydl.download([text])
if r_code == 0:
msg = '{} download successfully'.format(text)
except Exception:
pass
self.bot.send_message(chat.id, msg)
def run(self):
print 'Main loop started'
while True:
updates = self.bot.get_updates(
offset=self.last_update_id).wait()
try:
for update in updates:
if update.update_id > self.last_update_id:
self.last_update_id = update.update_id
self.process_message(update)
except Exception as ex:
print traceback.format_exc()
示例9: send_telegram
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def send_telegram(pdf):
"""
Отсылается сообщение через telegram bot. Получатель определяется по полю user.employee.sms_notify
:param pdf:
:return:
"""
d = shelve.open('shelve.db')
import_mode = d['IMPORT_MODE']
d.close()
logger.info('')
logger.info('――> Telegram:')
if import_mode:
logger.info('····skip due import mode')
return None
if pdf.upload_to_ctpbureau_status:
if pdf.ctpbureau.name == 'Admin':
# TODO прибито гвоздями; можно сделать в настройках что-то вроде, - пропускать, если есть стоп-слова в названии. Но опять таки - что пропускать? Аплоад? Смс? Нотификации? Если все пропускать, тогда дебажить не получится
# debugging purpose; if outputter is Admin then telegram send only to first superuser
receivers = Employee.objects.filter(user__is_superuser=True)
else:
receivers = Employee.objects.filter(telegram_notify=True)
for each in receivers:
telegram_id = each.telegram_id
bot = TelegramBot(settings.TELEGRAM_API_KEY)
message = """
№{} {}
Плит: {}, Машина: {}, Вывод: {}
""".format(pdf.order, pdf.ordername, str(pdf.plates),pdf.machines[1].name, pdf.ctpbureau.name)
# logger.debug('telegram_id={}'.format(telegram_id))
# logger.debug('username={}'.format(each.user.username))
responce = bot.send_message(chat_id=telegram_id, text=message).wait()
if isinstance(responce, twx.botapi.botapi.Message):
logger.info('··· {} receive notify'.format(responce.chat.username))
elif isinstance(responce, twx.botapi.botapi.Error):
logger.error(responce)
else:
logger.error('Critical telegram twx bug:')
logger.error(responce)
else:
# если по какой-то причине у нас не софрмирован upload_to_ctpbureau_status
logger.warning('····telegram NOT sent. Reason: failed upload')
示例10: Telegram
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
class Telegram(object):
def __init__(self, config, interpreter):
super().__init__()
self.__interpreter = interpreter
self.__logger = logging.getLogger('telegram')
logHandler = StreamHandler()
logHandler.setLevel(logging.DEBUG)
self.__logger.addHandler(logHandler)
self.__bot = TelegramBot(config['Telegram']['token'])
self.__logger.warning("Bot details: " + str(self.__bot.get_me().wait()))
self.__updateOffset = None
def send_msg(self, telegram_id, text):
self.__bot.send_message(telegram_id, text).wait()
def getUpdates(self, dbSession):
updates = None
try:
if self.__updateOffset is not None:
updates = self.__bot.get_updates(offset=self.__updateOffset + 1).wait()
else:
updates = self.__bot.get_updates().wait()
if updates is None:
raise Exception("No updates have been received due to an error")
except:
return
for update in updates:
if hasattr(update, 'message'):
self.__logger.warning(str(update.message.sender) + ": " + update.message.text)
self.__interpreter.interpret(dbSession, self, update.message.sender, update.message.text.split(' '))
if hasattr(update, 'update_id'):
self.__updateOffset = update.update_id
def shutdown(self):
pass
示例11: TelegramBroadcaster
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
class TelegramBroadcaster():
"""
Setup the bot
"""
def __init__(self):
self.bot = TelegramBot('<BOT_KEY>')
self.bot.update_bot_info().wait()
self.user_id = int(<CHANNEL_KEY>) # channel goyanglib
print(self.bot.username)
def send(self, message):
result = self.bot.send_message(self.user_id, message).wait()
print(result)
示例12: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
def main():
try:
with open('API_KEY', 'r') as f:
api_key = f.read().replace('\n', '')
except IOError:
print "please write the api key in file `API_KEY`"
exit(1)
bot = TelegramBot(api_key)
bot.update_bot_info().wait()
print(bot.username)
last_update_id = int(0)
while True:
try:
updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
for update in updates:
last_update_id = update.update_id
print(update)
process_update(bot, update)
global rems
for rem in rems:
if rem.when < datetime.now():
bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" +
unicode(rem.what))
print "removing reminder " + str(rem.id)
rems = [r for r in rems if r.id != rem.id]
print "rems = " + str(rems)
except KeyboardInterrupt:
# Allow ctrl-c.
raise KeyboardInterrupt
except Exception as e:
print "---\nException: "
print e
traceback.print_exc()
pass
示例13: db_connection
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
continue
db_connection()
for update in updates:
print(update)
offset = update.update_id + 1
msg = update.message
if msg is not None:
fromuser = msg.sender
txt = msg.text
check_new_chat(msg.chat.id)
if txt is not None:
humanname = fromuser.first_name
userid = fromuser.id
username = fromuser.username
if fromuser.last_name is not None:
humanname += ' ' + fromuser.last_name
print('From ' + humanname + ' ' + txt + ' (id ' + str(userid) + '): ' + txt)
if username == botmaster:
command_text = parse_command(txt)
if command_text is not None:
bot.send_message(msg.chat.id, command_text)
continue
parse_scene(txt, msg.chat.id)
except Exception as e:
print(e)
sleep(sleep_time)
db_conn.close()
示例14: TelegramBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
bot = TelegramBot('203607471:AAGIXeoretNObpGdN8lh1ecOQWUa5xY12c8')
bot.update_bot_info().wait()
print (bot.username)
last_update_id = 0
try:
while True:
updates = bot.get_updates(last_update_id+1).wait()
for update in updates:
last_update_id = update.update_id
reply, keyboard = get_message_reply(update.message)
bot.send_message(update.message.sender.id, reply, reply_markup = keyboard, parse_mode = 'Markdown')
# print ("sended "+reply)
time.sleep(0.5)
users = User.getAll(True, round(time.time())+1) #up to -5
for user in users:
if (user.progressKey == -1):
scenario.progress = (user.progressLabel, 0)
else:
scenario.progress = (user.progressLabel, user.progressKey)
if scenario.get_current().__class__.__name__ != "NodeMenu" and scenario.get_current().__class__.__name__ != "NodeReturn":
scenario.load(user)
reply, menu = scenario.next()
user.load(scenario)
user.lastMessage = round(time.time())
示例15: TelegramBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import send_message [as 别名]
from twx.botapi import TelegramBot
token = '<>'
bot = TelegramBot(token)
while True:
updates = bot.get_updates().wait()
for update in updates:
if update.message.text.startswith('/start'):
bot.send_message(update.message.chat.id, 'test message body')