コード例 #1
0
ファイル: chatbot.py プロジェクト: petr-tik/six_hack
    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))),
        ])
コード例 #2
0
ファイル: bot.py プロジェクト: ParleyMartins/no-spoiler-bot
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 ...')
コード例 #3
0
ファイル: bot.py プロジェクト: NeXidan/jigglypuff
 def start():
     telepot.DelegatorBot(
         consts.BOT['TOKEN'],
         [(
             per_chat_id(),
             create_open(Bot, timeout = 10)
         )]
     ).message_loop(run_forever = True)
コード例 #4
0
ファイル: bot.py プロジェクト: hojoonji/telegram-torrent
 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)),
   ])
コード例 #5
0
ファイル: main.py プロジェクト: nasfarley88/west313-bot
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)
コード例 #6
0
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)
コード例 #7
0
ファイル: main.py プロジェクト: Ziul/bot_howdoi
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 ...')
コード例 #8
0
ファイル: NUSQuestionBot.py プロジェクト: yewsiang/botmother
    def on_callback_query(self, msg):
        print "I shall do nothing from now on. Let CallbackBot handle the job"


def callback_function(msg):
    flavor = telepot.flavor(msg)
    if flavor == 'callback_query':
        print "callback!!"
    elif flavor == 'chat':
        print "normal message"
        return

def hello_world(self):
    print "hello"
    print self

mycallback = {'chat': hello_world,
    'callback_function': callback_function}

# callback_bot = telepot.Bot(TOKEN)
bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(MyBot, timeout=15)),
])
bot.message_loop(mycallback, run_forever=True)

'''
bot = CallbackBot(TOKEN)
bot.message_loop(callback_function, run_forever=True)
'''
コード例 #9
0
ファイル: ccal.py プロジェクト: ufian/CalcCalories
        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)
コード例 #10
0
ファイル: main.py プロジェクト: hgoori/MkrBot
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)
コード例 #11
0
ファイル: flask_counter.py プロジェクト: BlueVesper/telepot
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)
コード例 #12
0
ファイル: guess.py プロジェクト: illperipherals/telepot
            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 ...')
コード例 #13
0
ファイル: app.py プロジェクト: vasua/verycruelbot
            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)
コード例 #14
0
ファイル: main.py プロジェクト: ThomasKoscheck/Telegrambots
# user sent something that isnt text
            else:
                self.sender.sendMessage(
                    str('Bisher verstehe ich nur Textnachrichten und Bilder 😔')
                )
                self.sender.sendMessage(
                    str('Das wird sich in Zukunft aber sicher ändern!'))

        except Exception as e:
            # if any error accured in the try-block
            self.sender.sendMessage(
                str("Es ist nicht deine Schuld. \nAber bei mir ist etwas schief gelaufen. 😔 "
                    ))
            exc_type, exc_obj, exc_tb = sys.exc_info()
            log(message=unicode(exc_type).encode("utf-8") + ': ' +
                unicode(e).encode("utf-8") + ' : ' + username + ' : ' +
                'Input:' + input + ' : ' + strftime("%d.%m.%Y %H:%M") + ' : ' +
                'Line :' + unicode(exc_tb.tb_lineno).encode("utf-8"),
                path=errorfile,
                terminal=True)

TOKEN = 'your-bot-token'

# creating the bot
bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, ChatHandler, timeout=30),
])

# run the loop forever
bot.message_loop(run_forever='Listening ...')
コード例 #15
0
ファイル: alarm.py プロジェクト: hidercorp/teleapi
    # 2. Define event-handling function
    def on__alarm(self, event):
        print(event)  # see what the event object actually looks like
        self.sender.sendMessage('Beep beep, time to wake up!')

    def on_chat_message(self, msg):
        try:
            delay = float(msg['text'])

            # 3. Schedule event
            #      The second argument is the event spec: a 2-tuple of (flavor, dict).
            # Put any custom data in the dict. Retrieve them in the event-handling function.
            self.scheduler.event_later(delay, ('_alarm', {'payload': delay}))
            self.sender.sendMessage(
                'Got it. Alarm is set at %.1f seconds from now.' % delay)
        except ValueError:
            self.sender.sendMessage('Not a number. No alarm set.')


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, AlarmSetter, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
コード例 #16
0
ファイル: guess.py プロジェクト: xstpl/telepot
            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.message_loop(run_forever=True)
コード例 #17
0
                    "All commands are prefixed by a forward slash (/), with no spaces between the"
                    +
                    " slash and your command. Everyone has a seperate deck, which disappears after "
                    +
                    "10 minutes of inactivity. Dealt cards remain out of the deck until you issue a 'Majors', 'Minors', "
                    + "'Full', 'Settype', or 'Shuffle' command.\n " +
                    "These are the commands I currently understand:\n\n" +
                    "Majors -- Set deck to deal only from the Major Arcana\n" +
                    "Minors -- Set deck to deal only the pips\n" +
                    "Full -- Set deck to deal both Majors and Minors\n" +
                    "Listtypes -- List the types of decks available for use\n"
                    +
                    "Settype [type] -- Sets to one of the decks listed in Listtypes, eg: /settype "
                    + "jodocamoin Note: This reshuffles the deck\n" +
                    "Draw -- Draw a card\n" + "Help -- This text\n")

            self.decks[from_id] = self.deck


if __name__ == '__main__':
    token = sys.argv[1]
    setup_logger('sybil')
    logging.info('Starting bot with token {}'.format(token))
    sybil = telepot.DelegatorBot(
        token,
        [pave_event_space()(per_chat_id(), create_open, Sybil, timeout=600)])
    logging.info('Waiting for messages')
    MessageLoop(sybil).run_as_thread()
    while 1:
        time.sleep(1)
コード例 #18
0
ファイル: main.py プロジェクト: maartenberg/chatbotworkshop
    "/setup": commands.setup,
    "/playgame": commands.playgame,
}


class BattleshipBot(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(BattleshipBot, self).__init__(*args, **kwargs)

        # Initialiseer hier je state
        self.game_state = commands.GamePhase.NONE

    def on_chat_message(self, msg):
        cmd = self.get_command(msg)
        res = cmd(self, msg)

    def get_command(self, msg):
        firstword = msg['text'].split()[0]
        if '@' in firstword:
            firstword = firstword.split('@')[0]
        return commanddict.get(firstword, commands.catchall)


if __name__ == '__main__':
    TOKEN = os.environ.get('BOT_TOKEN', default=input('Token: '))
    bot = telepot.DelegatorBot(TOKEN, [
        pave_event_space()(
            per_chat_id(), create_open, BattleshipBot, timeout=1000006),
    ])
    bot.message_loop(run_forever=True)
コード例 #19
0
        f.write(newid + ':4:' + str(self._answers[4]) + ';')
        f.write(newid + ':5:' + str(self._answers[5]) + ';')
        f.write(newid + ':6:' + str(self._answers[6]) + ';')
        f.write(newid + ':7:' + str(self._answers[7]) + ';')
        f.write(newid + ':8:' + str(self._answers[8]) + ';')
        f.write(newid + ':9:' + str(self._answers[9]) + ';')
        f.write(newid + ':10:' + str(self._answers[10]) + ';')
        f.write(newid + ':11:' + str(self._answers[11]) + ';')
        f.write(newid + ':12:' + str(self._answers[12]) + ';' + '\n')
        f.close()
        g = open('users.txt', 'a')
        g.write(newid + ';' + '\n')
        g.close()


g = open('users.txt')
for line in g:
    knownUsers.append(int(line.split(';')[0]))

print(knownUsers)

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(types=['private']), create_open, Poll, timeout=10000),
])
print(bot.getMe())

MessageLoop(bot).run_as_thread()

while 1:
    time.sleep(10)
コード例 #20
0
ファイル: runbot.py プロジェクト: shamrad/test
            self.sender.sendMessage(text,reply_markup=key1)
            bot.editMessageReplyMarkup(msg_identifier=self._message_ind,reply_markup=None)
        else:
            pass


PORT = 9080



loop = asyncio.get_event_loop()
app = web.Application(loop=loop)

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
    pave_event_space())(per_chat_id(), create_open, Start, timeout=60),

])

webhook = OrderedWebhook(bot)
# bot.message_loop(run_forever='Listening ...')


loop.run_until_complete(init(app, bot))

loop.create_task(webhook.run_forever())

class Command(BaseCommand):
    try:
        web.run_app(app, port=PORT)
    except KeyboardInterrupt:
コード例 #21
0
def parseConfig(filename):
    f = open(filename, 'r')
    js = json.loads(f.read())
    f.close()
    return js

def getConfig(config):
    global TOKEN
    global AGENT_TYPE
    global VALID_USERS
    TOKEN = config['common']['token']
    AGENT_TYPE = config['common']['agent_type']
    VALID_USERS = config['common']['valid_users']
    if AGENT_TYPE == 'transmission':
        global transmission_user
        global transmission_password
        global transmission_port
        TRANSMISSION_USER = config['for_transmission']['transmission_user']
        TRANSMISSION_PASSWORD = config['for_transmission']['transmission_password']
        TRANSMISSION_PORT = config['for_transmission']['transmission_port']

config = parseConfig(CONFIG_FILE)
if not bool(config):
    print ("Err: Setting file is not found")
    exit()
getConfig(config)
bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(Torrenter, timeout=120)),
])
bot.notifyOnMessage(run_forever=True)
コード例 #22
0
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 ...')
コード例 #23
0
ファイル: plan.py プロジェクト: sepulchered/plan
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'
コード例 #24
0
ファイル: main.py プロジェクト: SotongDJ/telepot-momoco
        else:
            resul = Hande(msg['text'], self.argo)

            self.sending(mesag=resul.resut)
            self.argo = resul.argo
            if resul.cos == 1:
                self.close()
            elif resul.ekgu == 1:
                resul = Excut(msg['text'], self.argo)

                self.sending(mesag=resul.mesut)
                self.argo = resul.argo
                if resul.cos == 1:
                    self.close()

    def on__idle(self, event):  # Timeout Region
        usrdir = 'database/usr/' + str(
            self.argo.database.get('chat', {}).get('chatid', auth.id()))
        lingua = modDatabase.openSetting(usrdir=usrdir).get('lingua', 'enMY')
        self.sending(mesag=[msgMain.timesout + msgShort.cof])
        self.close()


key = json.load(open("database/key", "r"))
TOKEN = key["momocobot"]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, User, timeout=100),
])
bot.message_loop(run_forever='Listening ...')
コード例 #25
0
ファイル: bot.py プロジェクト: HassanHeydariNasab/hoy
                    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)

コード例 #26
0
ファイル: haeventbck.py プロジェクト: hafiz1401/bot-telegram
                print (from_id)
                unbind = db.unbind(from_id)
                sent = self.sender.sendMessage('Unbind berhasil. {}'.format(unbind))
                self._editor = telepot.helper.Editor(self.bot, sent)
                self._state = ''


        # elif query_data == 'data':
        #     sent = self.sender.sendMessage('\
        #         NIK------------:{}\n\
        #         Password---:{}\n\
        #         Nama--------:{}\n\
        #         Loker---------:{}'.format(self.data_user.get('nik'),
        #         self.data_user.get('password'),self.data_user.get('nama'),self.data_user.get('loker')))

# TOKEN = sys.argv[1]  # get token from command-line
TOKEN = '692089019:AAHR_d7I0VRer2BELku90RHlzP6m7fp14DY'
bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
    pave_event_space())(
        per_chat_id(), create_open, HadirEvent, timeout=100
    ),
])


MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
コード例 #27
0
ファイル: guess.py プロジェクト: salejovg/telepot
        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)
コード例 #28
0
ファイル: skel.py プロジェクト: pedroSR/BotMentor
            text +
            '\n\nThis message will disappear in 5 seconds to test deleteMessage',
            reply_markup=None)
        time.sleep(5)
        self.editor.deleteMessage()
        self.close()

    """
		casos = {'hClase':hClase, 'hCurso':hCurso,'profesores':profesores, 'clases':clases, 'fichas':fichas}
		query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
		casos[query_data](int(from_id),msg)
		text = str(casos[query_data])
		bot.answerCallbackQuery(query_id, text)
"""


TOKEN = "423194965:AAFJtn4HcgYQmR0oN6WoSAEHZljARFlBSeI"

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, BotMentorStarter, timeout=60),
    pave_event_space()(
        per_callback_query_origin(), create_open, BotMentor, timeout=300),
])

MessageLoop(bot).run_as_thread()
print('Listening ...')

# Keep the program running.
while 1:
    time.sleep(10)
コード例 #29
0
ファイル: bot.py プロジェクト: casassg/mcdaga
			if text.startswith('/'):
				self.handle_command(text,chat_id)
			else:
				self.sender.sendMessage('Hey!')
				self.close()

	def on_callback_query(self, msg):
		query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')

		if query_data == 'yes':
			self.cancel_last()
			self.sender.sendMessage(text='Yep')
		if query_data == 'no':
			self.cancel_last()
			self.sender.sendMessage(text='Nope')
		self.close()

	def on__idle(self, event):
		self.sender.sendMessage('You still there...?')

	def on_close(self, ex):
		a = 0



bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
            per_chat_id(), create_open, ChatHandler, timeout=10),
])
bot.message_loop(run_forever='Listening...')
コード例 #30
0
            * Какая погода в Москве сейчас(завтра, вчера)
            * Погода в Москве через n дней
            * Какая погода в Москве через n дней
            * Погода во вторник (и другие дни недели)
            * Москва через неделю
            * Погода в Москве через неделю
            * Вы можете отправить стикер\n
            Если вы опечатались в названии города или написали его с маленькой буквы, то правильный запрос будет выполнен\n
            Предложения по улучшению приветствуются @valeriia06''')
            else:
                handler = self.weather_answer.get_answer(msg['text'])
                self.sender.sendMessage(next(handler))

                url = request.urlopen(next(handler))

                self.sender.sendChatAction('upload_photo')
                self.sender.sendPhoto(('weather.png', url))
                url.close()

                self.sender.sendMessage(next(handler))


if __name__ == '__main__':
    bot = telepot.DelegatorBot(TOKEN, [
        delegate.pave_event_space()(delegate.per_chat_id(),
                                    delegate.create_open,
                                    WeatherGo,
                                    timeout=3600)
    ])
    bot.message_loop(run_forever='Waiting for your messages ...')
コード例 #31
0
ファイル: bot.py プロジェクト: riquellopes/shazam
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)
コード例 #32
0
ファイル: counter.py プロジェクト: Joukkue/JoukkueBot
import sys
import telepot
from telepot.delegate import per_chat_id, create_open
"""
$ python2.7 counter.py <token>

Count number of messages. Start over if silent for 10 seconds.
"""


class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, seed_tuple, timeout):
        super(MessageCounter, self).__init__(seed_tuple, timeout)
        self._count = 0

    def on_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)


TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(MessageCounter, timeout=10)),
])
bot.notifyOnMessage(run_forever=True)
コード例 #33
0
ファイル: app.py プロジェクト: samar-agrawal/pitalk
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)
コード例 #34
0
ファイル: telebot.py プロジェクト: cursecan/telewatch
        rjson = r.json()
        for msg in rjson:
            msgid = msg['id']
            subject = msg['subject']
            message = msg['message']
            r = requests.put(url=url + str(msgid) + '/',
                             data=json.dumps(payload),
                             headers={'Content-Type': 'application/json'})
            for user_tel in msg['send_to']:
                try:
                    bot.sendMessage(
                        user_tel['teleid'],
                        '<b>{0}</b>\n\n{1}\n\n<i>Salam, Warungid.com</i>'.
                        format(subject, message),
                        parse_mode='HTML')
                except:
                    pass


bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(types=['private']), create_open, Pulsabot, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

schedule.every(5).seconds.do(getMessagePost)

while 1:
    schedule.run_pending()
    time.sleep(1)
コード例 #35
0
# Simple Hangman Bot made for the 11th March CoderDojo Master
# Author: Giovanni Riva && Giovanni De Toni
# Mail: giovannimaria.riva at studenti.unitn.it
#       giovanni.detoni at studenti.unitn.it

import sys, time, telepot
from telepot.delegate import per_chat_id, create_open
from CoderDojoBot import CoderDojoBot

# Initialize the bot and start the loop
TOKEN = '187053440:AAEya33XgwHP8zcLXo1Ny5yOpJ2XvkwVRBU'
bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(CoderDojoBot, timeout=60)),
])
bot.notifyOnMessage(run_forever=True)
コード例 #36
0
        if self.currentCategory != len(self.categories):
            self.votes.append({
                str(self.categories[self.currentCategory]):
                self.candidates[self.currentCategory][int(query_data) - 1]
            })

            if self.currentCategory != len(self.categories) - 1:
                bot.sendMessage(from_id, 'Dale a  /siguiente')

        if self.currentCategory == len(self.categories) - 1:

            bot.sendMessage(from_id, 'Gracias por tu participación')
            with open(str(self.voter), 'w') as f:
                json.dump(self.votes, f)

        self.currentCategory += 1
        bot.answerCallbackQuery(query_id, text='Respuesta registrada')


TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(), create_open, MessageCounter, timeout=1000),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while True:
    time.sleep(10)
コード例 #37
0
ファイル: lover.py プロジェクト: VitaliyDuyunov/telepot
            self._cancel_last()
            self.sender.sendMessage('Thank you!')
            self.close()
        else:
            self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
            self._cancel_last()
            self._propose()

    def on__idle(self, event):
        self.sender.sendMessage('I know you may need a little time. I will always be here for you.')
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._count, self._edit_msg_ident)


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
            per_chat_id(types=['private']), create_open, Lover, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
コード例 #38
0
ファイル: telegram_bot.py プロジェクト: OnurBetn/BeerProject
            msg_dict = msg_dict['ALERT']
            if msg_dict['alert_status']:
                now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
                print(f"[{now}][{self.username}][{deviceID}] {msg_dict['resource']} ALERT received!")
                status = "OVER" if msg_dict['alert_type'] == "UP" else "UNDER"
                self.sender.sendMessage( 
                                emoji.emojize(f":warning: *WARNING - {deviceID}* :warning:\n{msg_dict['resource']} *{status}* the threshold!"),
                                parse_mode='Markdown'
                                )

    def on_close(self, ex):
        print(f"[{now}]Bot Closed")
        self.sender.sendMessage("Session closed. Type /start to start again.")


CATALOG_URL = 'http://localhost:8080/BREWcatalog/'
TOKEN = '962941325:AAEmgdul_4urnryImw4Rhiz3nsEAG3lz068'

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
            per_chat_id(types=['private']), create_open, BeerBot, timeout=3600),
])
MessageLoop(bot).run_as_thread()

now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
print(f"[{now}] Telegram Bot Started...")	

while 1:
    time.sleep(10)
コード例 #39
0
ファイル: clien_telegram.py プロジェクト: thkang0/home_util
    global TOKEN
    global VALID_USERS
    TOKEN = config['common']['token']
    VALID_USERS = config['common']['valid_users']

config = parseConfig(CONFIG_FILE)

if not bool(config):
    print ("Err: Setting file is not found")
    exit()

getConfig(config)

#TOKEN = '199048259:AAGtyE1_vvXFMEPQ24a3-qf8s4ifqPpP85U'
bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(ClienHelper, timeout=120)),
])

print(bot)
bot.notifyOnMessage(run_forever=True)





#curl "https://api.telegram.org/bot199048259:AAGtyE1_vvXFMEPQ24a3-qf8s4ifqPpP85U/sendMessage?chat_id=62233150&text=$startMsg"

#bot.sendMessage(my_chat_id, startMsg)


#show_keyboard = {'keyboard': [['Yes','No'], ['Maybe','Maybe not']]}
コード例 #40
0
import sys
import telepot
from telepot.delegate import pave_event_space, per_chat_id, create_open


class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0

    def on_chat_message(self, msg):
        self._count += 1
        self.sender.sendMessage(self._count)


TOKEN = sys.argv[1]  # get token from command-line

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, MessageCounter, timeout=10),
])
bot.message_loop(run_forever='Listening ...')
コード例 #41
0
        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'/newgame@' + 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)
コード例 #42
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        if query_data != 'start':
            self._score[self._answer == int(query_data)] += 1

        self._answer = self._show_next_question()

    def on__idle(self, event):
        text = '%d out of %d' % (self._score[True],
                                 self._score[True] + self._score[False])
        self.editor.editMessageText(text, reply_markup=None)
        self.close()


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, QuizStarter, timeout=3),
    pave_event_space()(
        per_callback_query_origin(), create_open, Quizzer, timeout=10),
])

MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
コード例 #43
0
ファイル: dimodo.py プロジェクト: HassanHeydariNasab/hoy
        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)
コード例 #44
0
            self._character_questions[self._current_question_num]['answers']
        info(self._username,
             'question: ' + self.question + '; choices: ' + str(choices))

        self._sent = self.sender.sendMessage(
            self.question,
            reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text=str(c), callback_data=str(c))
            ] for c in choices]))


TOKEN = sys.argv[1]
PROXY = sys.argv[2]

# https://89.165.218.82:47886
telepot.api.set_proxy(PROXY)

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(types=['private']),
        create_open,
        SprintStarter,
        timeout=54000),
])

MessageLoop(bot).run_as_thread()
info('Bot', 'Listening ...')

while 1:
    time.sleep(10)
コード例 #45
0
ファイル: router.py プロジェクト: BotsHackathon/telepot
import sys
import telepot
import telepot.helper
from telepot.delegate import per_chat_id, create_open

class 


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(, timeout=10))
])
bot.message_loop(run_forever=True)
コード例 #46
0
            self.sender.sendMessage('Надо ответить числом.')
            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:
            delta = datetime.utcnow() - self.start_time
            self.sender.sendMessage('Угадал !!! Время {} секунд'.format(
                delta.total_seconds()))
            self.close()

    def on__idle(self, event):
        self.sender.sendMessage(
            'Хорошая попытка. Время вышло. Правильный ответ %d' % self._answer)
        self.close()


TOKEN = os.getenv('TOKEN')

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(per_chat_id(), create_open, Player, timeout=30),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
コード例 #47
0
ファイル: __init__.py プロジェクト: yewsiang/botmother
        Command.process_commands(self, bot, msg)

    '''
    # Callback_query will be answered by CallbackBot. MainBot ignores such queries.
    def on_callback_query(self, msg):
        return
    '''

    def on_callback_query(self, msg):
        query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
        print "---- CALLBACK QUERY ----"
        CallbackQueries.on_answer(self, bot, data, query_id, msg['message']['message_id'])

    def on_close(self, exception):
        if isinstance(exception, telepot.exception.WaitTooLong):
            print "---- SESSION EXPIRED ----"
            self.sender.sendMessage('Session expired')


bot = telepot.DelegatorBot(TOKEN, [
    #
    # IMPORTANT: CallbackBot will NOT WORK if the program has been closed. You need one message to init it.
    # Assumption that timeout=None means the Bot will run forever
    # Note also: the message will run through CallbackBot first and then to MyBot
    #
    # (per_application(), create_open(CallbackBot, timeout=None)),
    (per_chat_id(), create_open(MainBot, timeout=None)),
])
# CANNOT put bot.message_loop() here or there will be a bug
コード例 #48
0
#!/usr/bin/env python3
import asyncio
import yaml
import telepot
from telepot.async.delegate import create_open
from telepot.delegate import per_chat_id

from tomatotimertgbot import Tomato

if __name__ == "__main__":
    config = yaml.load(open("config.yml", "r"))
    bot = telepot.async.DelegatorBot(
        config["telegram_bot_id"],
        [
            (per_chat_id(), create_open(
                Tomato, timeout=72*3600)),
        ])

    loop = asyncio.get_event_loop()
    loop.create_task(bot.messageLoop())
    loop.run_forever()

コード例 #49
0
ファイル: pairinga.py プロジェクト: August85/telepot
    def __init__(self, seed_tuple, timeout):
        super(UserHandlerSubclassInlineOnly, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result'])
        self._count = 0

    def on_message(self, msg):
        self._count += 1
        flavor = telepot.flavor(msg)

        print('%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance2(msg, flavor=flavor)))

    def on_close(self, exception):
        print('%s %d: closed' % (type(self).__name__, self.id))


TOKEN = sys.argv[1]

bot = telepot.async.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)),

    (per_from_id(), create_open(UserHandlerSubclass, timeout=20)),

    (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)),
])

loop = asyncio.get_event_loop()

loop.create_task(bot.messageLoop())
print('Listening ...')

loop.run_forever()
コード例 #50
0
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 ...')
コード例 #51
0
ファイル: vote.py プロジェクト: VitaliyDuyunov/telepot
        result = self._count_votes()
        self._close_ballot()
        self.sender.sendMessage('Time is up:\nYes: %d\nNo: %d\nSilent: %d' % result)

    def on_close(self, ex):
        global votes
        if self._ballot_box is None:
            try:
                del votes[self.id]
            except KeyError:
                pass
        else:
            votes[self.id] = (self._ballot_box, self._keyboard_msg_ident, self._expired_event)

        from pprint import pprint
        pprint(votes)


TOKEN = sys.argv[1]

bot = telepot.DelegatorBot(TOKEN, [
    include_callback_query_chat_id(
        pave_event_space())(
            per_chat_id(types=['group']), create_open, VoteCounter, timeout=10),
])
MessageLoop(bot).run_as_thread()
print('Listening ...')

while 1:
    time.sleep(10)
コード例 #52
0
        self._cancel_last()

        if self.class_to_find == 'Paladino' or self.class_to_find == 'Ranger':
            sent = self.sender.sendMessage(
                'Scegli il livello:', reply_markup=self.shortlevelKeyboard)
        else:
            sent = self.sender.sendMessage('Scegli il livello:',
                                           reply_markup=self.levelKeyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)

    def _send_menu(self, message='Ricerca incantesimo per:'):
        self._cancel_last()
        sent = self.sender.sendMessage(message, reply_markup=self.menuKeyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)


#Serious stuff
token = "token"

bot = telepot.DelegatorBot(token, [
    include_callback_query_chat_id(pave_event_space())(
        per_chat_id(types=['private']), create_open, Handler, timeout=3600)
])

MessageLoop(bot).run_as_thread()

print('Listening ...')

while 1:
    time.sleep(10)
コード例 #53
0
ファイル: myhome_util.py プロジェクト: thkang0/home_util
    js = json.loads(f.read())
    f.close()
    return js

def getConfig(config):
    global TOKEN
    global VALID_USERS
    TOKEN = config['common']['token']
    VALID_USERS = config['common']['valid_users']

config = parseConfig(CONFIG_FILE)

if not bool(config):
    print ("Err: Setting file is not found")
    exit()

getConfig(config)

bot = telepot.DelegatorBot(TOKEN, [
    (per_chat_id(), create_open(MyHomeHelper, timeout=120)),
])

bot.notifyOnMessage(run_forever=True)







コード例 #54
0
import telepot
from telepot.delegate import pave_event_space, per_chat_id, create_open
from telepot.loop import MessageLoop

from bot import Bot, clear_cache, load_articles
from log import log, config, clear_logs, logging, LOG_FILE

# Interval at which cache is cleared
CACHE_CLEAR_PERIOD = config['cache_clear_interval']
DEBUGGING = config['debugging']

# Delegator bot for multiple threaded instances of the Bot class
bot = telepot.DelegatorBot(config["token"], [
    pave_event_space()(
        per_chat_id(), create_open, Bot, timeout=10),
])


# Used to catch SIGINT and SIGTERM signals
class SignalProcess:
    kill_now = False

    def __init__(self):
        import signal

        signal.signal(signal.SIGINT, self.exit)
        signal.signal(signal.SIGTERM, self.exit)

    def exit(self, signum, frame):
        self.kill_now = True