本文整理汇总了Python中telepot.delegate.per_chat_id函数的典型用法代码示例。如果您正苦于以下问题:Python per_chat_id函数的具体用法?Python per_chat_id怎么用?Python per_chat_id使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了per_chat_id函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, token):
self._seen = set()
self._store = DBStore() # Imagine a dictionary for storing amounts.
super(ChatBox, self).__init__(token, [
# Here is a delegate to specially handle owner commands.
(per_chat_id(), create_open(TransferHandler, 60*5, self._store, self._seen)),
(per_chat_id(), create_open(OwnerHandler, 60*5, self._store, self._seen)),
(per_chat_id(), create_open(FirstTimeHandler, 60*5, self._store, self._seen))
# For senders never seen before, send him a welcome message.
# (self._is_newcomer, custom_thread(call(self._send_welcome))),
])
开发者ID:petr-tik,项目名称:six_hack,代码行数:12,代码来源:chatbot.py
示例2: start
def start():
telepot.DelegatorBot(
consts.BOT['TOKEN'],
[(
per_chat_id(),
create_open(Bot, timeout = 10)
)]
).message_loop(run_forever = True)
开发者ID:NeXidan,项目名称:jigglypuff,代码行数:8,代码来源:bot.py
示例3: main
def main():
config = resource_filename(__name__, 'configs.yaml')
config = yaml.load(open(config).read())
bot = telepot.DelegatorBot(config['token'], [
(per_inline_from_id(), create_open(NoSpoiler, timeout=30)),
(per_chat_id(), create_open(NoSpoiler, timeout=2)),
])
bot.message_loop(run_forever='Running ...')
开发者ID:ParleyMartins,项目名称:no-spoiler-bot,代码行数:8,代码来源:bot.py
示例4: __init__
def __init__(self, token, search, db, server):
self.search = search
self.db = db
self.server = server
super(ChatBox, self).__init__(token,
[
(per_chat_id(), create_open(T2bot, 90, self.search, self.db, server)),
(per_application(), create_open(JobMonitor, self.server, self.db)),
])
开发者ID:hojoonji,项目名称:telegram-torrent,代码行数:10,代码来源:bot.py
示例5: main
def main():
"""Simple main."""
import config
bot = telepot.DelegatorBot(config.TG_KEY, [
(per_chat_id(), create_open(WestieBot, timeout=10)),
])
bot.message_loop()
while not EXITAPP:
time.sleep(1)
开发者ID:nasfarley88,项目名称:west313-bot,代码行数:11,代码来源:main.py
示例6: main_loop
def main_loop(app, queue=None):
"""Main loop of the bot.
:param flask.app.Flask app: Flask app.
:param queue: Update queue to be used as the source of updates instead of the Telegram API server. Used in tests.
"""
bot = DelegatorBot(
TELEGRAM_TOKEN,
[pave_event_space()(per_chat_id(), create_open, ChoreBot, timeout=TELEGRAM_IDLE_TIMEOUT, flask_app=app)],
)
forever = False if queue else "Listening ({})...".format(app.config["ENV"])
bot.message_loop(source=queue, run_forever=forever)
开发者ID:andreoliwa,项目名称:python-dontforget,代码行数:12,代码来源:telegram_bot.py
示例7: main
def main():
# Get the dispatcher to register handlers
bot = telepot.DelegatorBot(token, [
(per_inline_from_id(), create_open(HowDoIBot, timeout=30)),
(per_chat_id(), create_open(HowDoIBot, timeout=10)),
])
logger.info('Starting bot')
# bot.message_loop({'inline_query': on_inline_query,
# 'chosen_inline_result': on_chosen_inline_result,
# 'chat': on_chat_message},
# run_forever='Listening ...')
bot.message_loop(run_forever='Listening ...')
开发者ID:Ziul,项目名称:bot_howdoi,代码行数:13,代码来源:main.py
示例8: open
if m[0] == u'mojose':
r = msg
elif user_id == 170378225:
'''
if m[1] == u'source':
f = open("bot.py", 'r')
self.sender.sendDocument(f)
elif and m[1] == u'k':
process = subprocess.Popen(['/bin/bash'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write('(sleep 5 && ./bot_killer.sh)&\n')
sleep(2)
process.kill()
#print process.stdout.readline()
'''
process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,bufsize = 1, universal_newlines = True)
process.stdin.write(mr+';echo nenio!\n')
r = process.stdout.readline()
process.kill()
if r == "":
r = "error!"
if len(r) > 4000:
r = u'too long!'
self.sender.sendMessage(r,parse_mode='HTML')
TOKEN = '208704782:AAErS5HiEKZxBuIAwOm4LP3zoZEBqVOSGxQ'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(Babilo, timeout=1)),
])
bot.message_loop(run_forever=True)
开发者ID:HassanHeydariNasab,项目名称:hoy,代码行数:30,代码来源:dimodo.py
示例9: int
self.sender.sendMessage('Give me a number, please.')
return
try:
guess = int(msg['text'])
except ValueError:
self.sender.sendMessage('Give me a number, please.')
return
# check the guess against the answer ...
if guess != self._answer:
# give a descriptive hint
hint = self._hint(self._answer, guess)
self.sender.sendMessage(hint)
else:
self.sender.sendMessage('Correct!')
self.close()
def on__idle(self, event):
self.sender.sendMessage('Game expired. The answer is %d' % self._answer)
self.close()
TOKEN = sys.argv[1]
bot = telepot.DelegatorBot(TOKEN, [
pave_event_space()(
per_chat_id(), create_open, Player, timeout=10),
])
bot.message_loop(run_forever='Listening ...')
开发者ID:illperipherals,项目名称:telepot,代码行数:30,代码来源:guess.py
示例10: chkNConv
all_games[game_id].player_list.append(Player(msg['from']['id'], msg['from']['first_name']))
start_url = telegram_base_url + bot_name + '?start=' + game_id.__str__()
self.sender.sendMessage(text=bot_invite_player % (chkNConv(msg['from']['first_name']),
chkNConv(bot_name),
chkNConv(start_url)))
def on_message(self, msg):
print(u'on_message() is being called')
flavor = telepot.flavor(msg)
# normal message
if chkNConv(flavor) == u'normal':
content_type, chat_type, _chat_id = telepot.glance2(msg)
print('Normal Message:', content_type, chat_type, _chat_id, '; message content: ', msg)
if content_type == 'text':
if self._convert_type == ConverType.nothing:
if chkNConv(msg['text']) == u'/start':
self.sender.sendMessage(text=bot_starting_script)
elif chkNConv(msg['text']) == u'/newgame' or chkNConv(msg['text']) == u'/[email protected]' + chkNConv(bot_name):
self.create_game(msg=msg)
else:
raise telepot.BadFlavor(msg)
TOKEN = sys.argv[1] # get token from command-line
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(LiarsDiceBot, timeout=120)),])
print('Listening ...')
bot.notifyOnMessage(run_forever=True)
开发者ID:daedaluschan,项目名称:telegram_liars_dice,代码行数:30,代码来源:liars_dice_bot.py
示例11: Planner
BOT_API_TOKEN = os.environ.get('BOT_TOKEN', '')
BOT_HOOK_URL = os.environ.get('BOT_HOOK_URL', '/bot/hook')
BOT_HOST = os.environ.get('BOT_HOST', '')
# bot related
class Planner(telepot.helper.ChatHandler):
def __init__(self, *args, **kwargs):
super(Planner, self).__init__(*args, **kwargs)
def on_chat_message(self, msg):
self.sender.sendMessage('gigla')
bot = telepot.DelegatorBot(BOT_API_TOKEN, [
pot_delegate.pave_event_space()(
pot_delegate.per_chat_id(),
pot_delegate.create_open,
Planner,
timeout=15
)
])
webhook = pot_loop.OrderedWebhook(bot)
# server related
app = flask.Flask(__name__)
@app.route('/')
def index():
return 'planner bot'
开发者ID:sepulchered,项目名称:plan,代码行数:30,代码来源:plan.py
示例12: ConfigParser
logger = logging.getLogger('reminder')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(ch)
ch = logging.FileHandler(filename="debug.log")
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(ch)
# Parse a config
config = ConfigParser().load("setting.json")
if not config:
logging.error("Err: Nothing to be parsed")
valid_users = config['valid_chat_id']
# Start scheduler
mainSchedule = BackgroundScheduler(timezone=config['default_time_zone'])
mainSchedule.start()
# Job store for scheduler
jobStore = dict()
schedStore = dict()
bot = telepot.DelegatorBot(config['token'], [
pave_event_space()(
per_chat_id(), create_open, Reminder, timeout=10),
])
bot.message_loop(run_forever='Listening ...')
开发者ID:seungjuchoi,项目名称:Telegram-notify-from-sqlite,代码行数:30,代码来源:telegram_reminder.py
示例13: int
if content_type != 'text':
self.sender.sendMessage('Give me a number, please.')
return
try:
guess = int(msg['text'])
except ValueError:
self.sender.sendMessage('Give me a number, please.')
return
# check the guess against the answer ...
if guess != self._answer:
# give a descriptive hint
hint = self._hint(self._answer, guess)
self.sender.sendMessage(hint)
else:
self.sender.sendMessage('Correct!')
self.close()
def on_close(self, exception):
if isinstance(exception, telepot.helper.WaitTooLong):
self.sender.sendMessage('Game expired. The answer is %d' % self._answer)
TOKEN = sys.argv[1]
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(Player, timeout=10)),
])
bot.notifyOnMessage(run_forever=True)
开发者ID:salejovg,项目名称:telepot,代码行数:30,代码来源:guess.py
示例14: reply_to_badgay
return False
def reply_to_badgay(self, content_type, m):
if content_type == 'text' and 'хуй' in m.text:
self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id)
def on_message(self, msg):
content_type, chat_type, chat_id = telepot.glance2(msg)
m = telepot.namedtuple(msg, 'Message')
if chat_id < 0:
# public chat
if not self.reply_to_kek(content_type, m):
self.reply_to_badgay(content_type, m)
else:
# private conversation
self.reply_to_badgay(content_type, m)
"""
def on_close(self, exception):
if isinstance(exception, telepot.helper.WaitTooLong):
bot.notifyOnMessage(run_forever=True)
"""
TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4'
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(VeryCruel, timeout=1)),
])
bot.notifyOnMessage(run_forever=True)
开发者ID:vasua,项目名称:verycruelbot,代码行数:30,代码来源:app.py
示例15: dict
if 'cb_message' in self.context and self.context['cb_message'] != self.context.get('last_message'):
stage.base_message(
'Finish',
update_msg=self.context['cb_message'],
with_keyboard= 'last_message' not in self.context
)
if 'last_message' in self.context:
self.user_config.data['last_message'] = self.context['last_message']
self.user_config.context = dict()
self.user_config.save()
if __name__ == '__main__':
conn = get_connect()
params = list(model.GlobalConfig.objects.timeout(True))
bot = telepot.DelegatorBot(config.BOT_TOKEN, [
pave_event_space()(
[per_chat_id(('private',)), per_callback_query_chat_id(('private',))],
create_open,
EatSession,
include_callback_query=True, timeout=300),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')
while 1:
time.sleep(10)
开发者ID:ufian,项目名称:CalcCalories,代码行数:31,代码来源:ccal.py
示例16: MessageProcessor
class MessageProcessor(telepot.helper.ChatHandler):
'''Initiate chat socket for a client and respond to the input query'''
def __init__(self, seed_tuple, timeout):
super(MessageProcessor, self).__init__(seed_tuple, timeout)
def on_chat_message(self, msg):
'''process and response message'''
ntuple = Message(**msg)
if telepot.glance(msg)[0] == 'text':
if any(q in ntuple.text for q in ACTION_DICT.keys()):
response = perform_action(ntuple.text, ntuple.from_.id)
else:
response = KERNEL.respond(ntuple.text)
#if not response:
#response = self.sender.sendMessage(
# chat_id, 'I do not understand your last message.', reply_to_message_id=msg_id)
self.sender.sendMessage(response)
BOT = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageProcessor, timeout=10)),
])
BOT.message_loop(run_forever=True)
开发者ID:samar-agrawal,项目名称:pitalk,代码行数:29,代码来源:app.py
示例17: create_open
import sys
import telepot
from telepot.delegate import per_chat_id, create_open
from mkr_bot import MkrBot
token = sys.argv[1]
log_path = sys.argv[2]
bot = telepot.DelegatorBot(token, [(per_chat_id(), create_open(MkrBot, timeout=10, log_path=log_path, log_level=10))])
print(bot.getMe())
bot.notifyOnMessage(run_forever=True)
开发者ID:hgoori,项目名称:MkrBot,代码行数:11,代码来源:main.py
示例18: ProcessMessage
import telepot
import logging
from taxas import Fabrica
from telepot.delegate import per_chat_id, create_open
SHAZAM_TOKEN = os.environ.get("SHAZAM_TOKEN")
logr = logging.getLogger(os.environ.get("LOG-NAME"))
class ProcessMessage(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(ProcessMessage, self).__init__(seed_tuple, timeout)
def on_message(self, msg):
try:
if msg['text'][0] == "/":
taxa = msg['text'][1:].lower()
Fabrica.destroy()
fabrica = Fabrica(taxa=taxa)
self.sender.sendMessage(fabrica.get())
except Exception as e:
logr.error(e, exc_info=True)
bot = telepot.DelegatorBot(SHAZAM_TOKEN, [
(per_chat_id(), create_open(ProcessMessage, timeout=10)),
])
print('Listening ...')
bot.notifyOnMessage(run_forever=True)
开发者ID:riquellopes,项目名称:shazam,代码行数:30,代码来源:bot.py
示例19: choice
if r == '':
raise
except Exception as e:
if re.search(u'(نظرت|نظر تو) (در مورد|درباره|دربارهٔ|درباره ی|دربارهی|راجع به|راجب) .* (چیست|چیه)', mr):
r = choice([u'در مورد همه چی باید نظر بدم؟!', u'نظر خاصی ندارم.', u'در این زمینه صاحب نظر نیستم.'])
elif re.search(u'؟$', mr):
r = choice([u'چرا میپرسی؟', u'نپرس!', u'نمیدونم.'])
elif re.search(u'!$', mr):
r = choice([u'عجب!', u'چه جالب!'])
elif re.search(u'\.$', mr):
r = choice([u'این که پایان جملهت نقطه گذاشتی خیلی عالیه! ولی معنی جملهت رو نمیفهمم. یادم بده.'])
else:
r = u'نمیفهمم چی میگی. بیا خصوصی یادم بده!'
#print 'erorr:', e
#r = e
if len(r) > 0:
self.sender.sendMessage(r,parse_mode='HTML')
if __name__ == "__main__":
if len(sys.argv) == 2:
if sys.argv[1] == 'd':
TOKEN = '185401678:AAF_7PbchYOIDAKpy6lJqX7z01IsFgDTksA'
else:
o = open(os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'token'))
t = o.read()
TOKEN = t[:-1]
o.close()
bot = telepot.DelegatorBot(TOKEN, [(per_chat_id(), create_open(Babilo, timeout=1)),])
bot.message_loop(run_forever=True)
开发者ID:HassanHeydariNasab,项目名称:hoy,代码行数:29,代码来源:bot.py
示例20: MessageCounter
class MessageCounter(telepot.helper.ChatHandler):
def __init__(self, seed_tuple, timeout):
super(MessageCounter, self).__init__(seed_tuple, timeout)
self._count = 0
def on_chat_message(self, msg):
self._count += 1
self.sender.sendMessage(self._count)
TOKEN = sys.argv[1]
PORT = int(sys.argv[2])
URL = sys.argv[3]
app = Flask(__name__)
update_queue = Queue() # channel between `app` and `bot`
bot = telepot.DelegatorBot(TOKEN, [
(per_chat_id(), create_open(MessageCounter, timeout=10)),
])
bot.message_loop(source=update_queue) # take updates from queue
@app.route('/abc', methods=['GET', 'POST'])
def pass_update():
update_queue.put(request.data) # pass update to bot
return 'OK'
if __name__ == '__main__':
bot.setWebhook(URL)
app.run(port=PORT, debug=True)
开发者ID:BlueVesper,项目名称:telepot,代码行数:30,代码来源:flask_counter.py
注:本文中的telepot.delegate.per_chat_id函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论