Exemple #1
0
from telegram.ext import Filters, Updater, CommandHandler, InlineQueryHandler, ConversationHandler, RegexHandler, MessageHandler
from telegram import InlineQueryResultArticle, InputTextMessageContent, ReplyKeyboardMarkup, ReplyKeyboardRemove, ChatAction
from intents import intents
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData

CHOOSING_START, SUBSCRIBE, COMPANY, TYPING_REPLY = range(4)
'''Reading config details'''
config = ConfigParser()
config.readfp(open('intents.config'))
token = config.get('settings', 'token')
typing_time = config.getint('settings', 'typing_time')
db_url = config.get('settings', 'DB_URL')

print(token)
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)
logger = logging.getLogger(__name__)

meta = MetaData()
engine = create_engine(db_url, echo=True)
'''Initialising table'''
users = Table(
    'users',
    meta,
    Column('email_id', String, primary_key=True),
    Column('company_name', String),
Exemple #2
0

if __name__ == "__main__":
    #TOKEN = open('API_TOKEN','r').read().replace('\n','')
    TOKEN = os.environ.get('API_TOKEN')

    NAME = "veg-pokebot"

    # Port is given by Heroku
    PORT = os.environ.get('PORT')

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

    updater = Updater(TOKEN, use_context=True)

    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CommandHandler('about', about))
    updater.dispatcher.add_handler(CommandHandler('help', get_help))
    updater.dispatcher.add_handler(CommandHandler('pokedex', all_info))
    updater.dispatcher.add_handler(CommandHandler('type', get_type))
    updater.dispatcher.add_handler(CommandHandler('pic', get_pic))
    updater.dispatcher.add_handler(CommandHandler('ability', ability))
    updater.dispatcher.add_handler(CommandHandler('learnset', learnset))
    updater.dispatcher.add_handler(CommandHandler('random', get_random))
    updater.dispatcher.add_handler(CommandHandler('starter', starter))
    updater.dispatcher.add_handler(CommandHandler('evolution', evolution))
    updater.dispatcher.add_handler(CommandHandler('evolearnset', evolearnset))

    # Start the webhook
Exemple #3
0
    update.message.reply_text('Я помогу. Но не сегодня.')


def add_public(bot, update):
    update.message.reply_text('Окей. Вставь ссылку на паблик в ответ.')


def ask_for_all_pics(bot, update):
    update.message.reply_text('Вот все твои пикчи.')


def ask_for_pics_from_one_public(bot, update):
    update.message.reply_text(
        'Окей. Из какого паблика ты хочешь получить пикчи?')


def get_pics():
    pass


updater = Updater('316772437:AAH0AbTWmNcb0OlsTFvfso4hE4AyhjJuS-8')
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('help', help_))
updater.dispatcher.add_handler(CommandHandler('addpub', add_public))
updater.dispatcher.add_handler(CommandHandler('getall', ask_for_all_pics))
updater.dispatcher.add_handler(
    CommandHandler('getone', ask_for_pics_from_one_public))

updater.start_polling()
updater.idle()
Exemple #4
0
        website.save()


# send msg via bot
def sendMsg(bot, chat_id, text):
    try:
        bot.sendMessage(chat_id=chat_id, text=text)
        return 1
    except:
        print("EXCEPTION while sending Message: \n%s" % (text))
        return 0


## MAIN
updater = Updater(TELEGRAM_API_KEY)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler("add", add, pass_args=True))
updater.dispatcher.add_handler(CommandHandler("del", delete, pass_args=True))
updater.dispatcher.add_handler(CommandHandler("list", url_list))
updater.dispatcher.add_handler(CommandHandler("test", test, pass_args=True))
updater.dispatcher.add_handler(CommandHandler("help", show_help))

print('Telegram bot started\n')
updater.start_polling(poll_interval=1)

while True:
    if (datetime.datetime.now() >
            lastCall + datetime.timedelta(seconds=CHECK_INTERVAL)):
        lastCall = datetime.datetime.now()
        check()

# Handler for the /cancel command.
# Sets the state back to MENU and clears the context
def cancel(bot, update):
    chat_id = update.message.chat_id
    del state[chat_id]
    del context[chat_id]


def help(bot, update):
    bot.sendMessage(update.message.chat_id, text="Use /set to test this bot.")


# Create the Updater and pass it your bot's token.
updater = Updater(TOKEN)

# The command
updater.dispatcher.add_handler(CommandHandler('set', set_value))
# The answer and confirmation
updater.dispatcher.add_handler(MessageHandler([Filters.text], set_value))
updater.dispatcher.add_handler(CommandHandler('cancel', cancel))
updater.dispatcher.add_handler(CommandHandler('start', help))
updater.dispatcher.add_handler(CommandHandler('help', help))

# Start the Bot
updater.start_polling()

# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
Exemple #6
0
import telegram
import config
import logging
from telegram.ext import Updater, MessageHandler, CommandHandler, Filters
import LogicHandler, Parser, Error

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

bot = telegram.Bot(token=config.token)
updater = Updater(token=config.token)
dispatcher = updater.dispatcher

msg_for_comparison = []

# def start(bot, update):
#   bot.send_message(chat_id=update.message.chat_id, text='Hi! /help if you need more instructions')


def parseInput(bot, update):
    msgText = update.message.text.replace("/parsethis ", "")
    if (Error.error(msgText)):
        bot.send_message(chat_id=update.message.chat_id,
                         text="Error in Notation! Try Again!",
                         parse_mode="Markdown")
    else:
        predicateFn = LogicHandler.stringToFn(Parser.textToLogic(msgText))
        params = Parser.paramsGetter(msgText)
        res = LogicHandler.getTable(predicateFn, params)
Exemple #7
0
import os
from telegram.ext import Updater, CommandHandler
updater = Updater(token=os.environ['TOKEN'])


def hello(bot, update):
    update.message.reply_text('Hello {}'.format(
        update.message.from_user.first_name))


updater.dispatcher.add_handler(CommandHandler('hello', hello))

updater.start_polling()
updater.idle()
Exemple #8
0
 def setUp(self):
     # For use within the tests we nee some stuff. Starting with a Mockbot
     self.bot = Mockbot()
     # And an InlineQueryGenerator and updater (for use with the bot.)
     self.iqg = InlineQueryGenerator(self.bot)
     self.updater = Updater(bot=self.bot)
Exemple #9
0
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                     level=logging.INFO)


def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

def echo(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)


if __name__ == '__main__':


    updater = Updater('1677667809:AAHH2KzZBHJl4NPS8Jqjrw4bMl6VYviQ8ac')

    dispatcher = updater.dispatcher
    start_handler = CommandHandler('start', start)
    dispatcher.add_handler(start_handler)



    echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
    dispatcher.add_handler(echo_handler)


    def caps(update, context):
        text_caps = ' '.join(context.args).upper()
        context.bot.send_message(chat_id=update.effective_chat.id, text=text_caps)
    caps_handler = CommandHandler('caps', caps)
Exemple #10
0
import json
import random
import os
import dotenv
from telegram.ext import Updater

dotenv.load_dotenv('.env')
TOKEN = os.getenv('TOKEN')

updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher

import logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)


def start(update, context):
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=
        "Hi there , Im random Roti ( Rules Of The Internet ) bot , send /rroti to get a random rule .\n\n Made by github.com/robimez"
    )


def rroti(update, context):
    with open('./rules_of_the_internet.json', encoding="utf8") as f:
        data = json.load(f)
        context.bot.send_message(
            chat_id=update.effective_chat.id,
import threading
import os



from iotcontrol import iotcontrol
from telegram import InlineKeyboardButton, InlineKeyboardMarkup

from telegram.ext import Updater
from telegram.ext import CommandHandler , CallbackQueryHandler
from telegram.ext import MessageHandler, Filters
import logging
##############################################################################################
darkskyKey = '<Enter dark sky token>'
updater = Updater(token='<TELEGRAM TOKEN>') #Insert bot token
#required by bot to execute functions see example: https://python-telegram-bot.org/
control = iotcontrol(1234567,darkskyKey,33.8463634,-84.373057) 
# 1234567 is example admin id : find yours by going to web-api of telegram: https://api.telegram.org/bot<TOKEN>/getUpdates
#<TOKEN> is telegram token during bot creation
#read: https://zenofall.com/raspberry-pi-telegram-home-automation/
#replace: 33.8463634,-84.373057 by latitude longitude of your location from google maps
#we use adminId for special privileges on the bot

dispatcher = updater.dispatcher 
#bot examples: https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples

#logging is always good

#define logging format and file location
Exemple #12
0
def main():
    locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8')

    conf = confighelper.ConfigHelper(sys.argv[1])
    updater = Updater(token=conf.get_anastasia_key())
    dispatcher = updater.dispatcher

    mongoda.MongoDA.init(conf)

    room = roomcommand.RoomCommand(loghelper.log, conf.path_ics())
    todo = todolist.Todo()
    nudeModule = nude

    start_handler = CommandHandler('room', room.give_room)
    joke_handler = CommandHandler('joke', joke.give_joke)
    blc_handler = CommandHandler('blc', joke.give_blc)
    todo_handler = CommandHandler('todo', todo.give_todo, pass_args=True)
    addtodo_handler = CommandHandler('addtodo',
                                     todo.give_add_todo,
                                     pass_args=True)
    keskonmange_handler = CommandHandler('keskonmange', new_eat)
    weather_handler = CommandHandler('weather',
                                     weather.give_weather,
                                     pass_args=True)
    airquality_handler = CommandHandler('airquality',
                                        airquality.give_airquality,
                                        pass_args=True)
    nude_handler = CommandHandler('nude', nudeModule.get_nude, pass_args=True)
    chatte_handler = CommandHandler('chatte', joke.get_chatte)
    help_handler = CommandHandler('help', help.give_credits)
    fact_handler = CommandHandler('fact', fact.give_fact)
    citation_handler = CommandHandler('citation', fact.give_citation)
    chienne_handler = CommandHandler('chienne', joke.get_chienne)
    kappa_handler = CommandHandler('kappa', joke.send_kappa)

    callback_handler = CallbackQueryHandler(eat_callback)
    callback_handler_todo = CallbackQueryHandler(todo.todo_callback)

    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(joke_handler)
    dispatcher.add_handler(blc_handler)
    dispatcher.add_handler(todo_handler)
    dispatcher.add_handler(addtodo_handler)
    dispatcher.add_handler(keskonmange_handler)
    dispatcher.add_handler(callback_handler, group=0)
    dispatcher.add_handler(callback_handler_todo, group=1)
    dispatcher.add_handler(weather_handler)
    dispatcher.add_handler(airquality_handler)
    dispatcher.add_handler(nude_handler)
    dispatcher.add_handler(help_handler)
    dispatcher.add_handler(chatte_handler)
    dispatcher.add_handler(fact_handler)
    dispatcher.add_handler(citation_handler)
    dispatcher.add_handler(chienne_handler)
    dispatcher.add_handler(kappa_handler)

    if not conf.get_webhook():
        updater.start_polling()
    else:
        updater.start_webhook(listen='0.0.0.0',
                              port=int(conf.get_webhook_port()),
                              url_path=conf.get_anastasia_key(),
                              key=conf.get_webhook_private_ssl(),
                              cert=conf.get_webhook_certif(),
                              webhook_url=conf.get_webhook_adress() + ":" +
                              conf.get_webhook_port() + "/" +
                              conf.get_anastasia_key())

    updater.start_polling()
Exemple #13
0
import random

import sqlite3
from telegram.error import BadRequest

from telegram.ext import Updater, CommandHandler
from telegram.ext import dispatcher

conn = sqlite3.connect('users.db')

users_id = [
    928026036, 923626248, 460729305, 405196888, 375832364, 368778663,
    346956156, 228829286
]

updater = Updater("923626248:AAHT1GVNcdDvdUjW6zDYrQ04biRJk4CRfhY",
                  use_context=True)

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO)


def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="I'm a bot, please talk to me!")


def hello(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='Que te pasa puta? queres que te la ponga?')
Exemple #14
0
from telegram.ext import Updater, CommandHandler, Filters, MessageHandler
import logging

updater = Updater(token="651324863:AAHFpPhxnJSisqWidTlfU9MrgQ8P-uLTJ6s")
dispatcher = updater.dispatcher

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

def start(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text="Hola, como estás?")

def echo(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text=update.message.text)

def caps(bot, update, args):
    textCaps = ' '.join(args).upper()
    bot.send_message(chat_id=update.message.chat_id, text=textCaps)

def unknown(bot, update):
    bot.send_message(chat_id=update.message.chat_id, text="Lo siento, no he entendido el comando.")

def setRacoToken(self, token):
    racoToken = token

startHandler = CommandHandler('start', start)
capsHandler = CommandHandler('caps', caps, pass_args=True)
echoHandler = MessageHandler(Filters.text, echo)
unknownHandler = MessageHandler(Filters.command, unknown)

dispatcher.add_handler(startHandler)
dispatcher.add_handler(capsHandler)
Exemple #15
0
def clean_up(conn, cur):
    cur.close()
    conn.close()


if __name__ == "__main__":
    TOKEN = ''
    # telegram bot related information
    bot = telegram.Bot(token=TOKEN)

    # Initializing the DB
    conn, cur = connect_sqlite3("announcement.db")

    updater = Updater(token=TOKEN,
                      use_context=True,
                      request_kwargs={
                          'read_timeout': 6,
                          'connect_timeout': 7
                      })
    dispatcher = updater.dispatcher

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

    start_handler = CommandHandler('start', start)
    leave_handler = CommandHandler('leave', leave)
    dispatcher.add_handler(start_handler)
    dispatcher.add_handler(leave_handler)
    updater.start_polling()

    while True:
def start_polling(token: str, db_uri: str):
    setup_database_engine(db_uri)
    updater = Updater(token, use_context=True)
    setup_handlers(updater)
    updater.start_polling()
    updater.idle()
def getJson(useText, jsondata):
    keys = [key for key in jsondata]

    returnvalue = "안물안궁"

    for key in keys:
        if key in useText:
            returnvalue = jsondata[key]

    return returnvalue


def get_message(update, context):
    with open("./json_test.json", "r", encoding='UTF8') as json_file:
        jsondata = json.load(json_file)

    useText = update.message.text

    if "실시간차트" in useText:
        update.message.reply_text(getMelonChart())
    else:
        update.message.reply_text(getJson(useText, jsondata))


updater = Updater(bot_id, use_context=True)

message_handler = MessageHandler(Filters.text, get_message)
updater.dispatcher.add_handler(message_handler)

updater.start_polling(timeout=3, clean=True)
updater.idle()
def start_webhook(token: str, db_uri: str, port: int):
    setup_database_engine(db_uri)
    updater = Updater(token, use_context=True)
    setup_handlers(updater)
    updater.start_webhook(port=port)
    updater.idle()
def main():
    updater = Updater('KEY')
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('start', start))
    updater.start_polling()
    updater.idle()
Exemple #20
0
                               set_techo),
                MessageHandler(Filters.regex(constantes.REGEX_ONLY_STRINGS),
                               error_letra)
            ],
            S_ERROR: [
                MessageHandler(Filters.regex(constantes.REGEX_ONLY_NUMBERS),
                               set_error),
                MessageHandler(Filters.regex(constantes.REGEX_ONLY_STRINGS),
                               error_letra)
            ],
        },
        fallbacks=[MessageHandler(Filters.regex('^Volver$'), done)])


if __name__ == '__main__':
    import logging

    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

    logger = logging.getLogger(__name__)
    BOT_KEY = os.environ['BOT_KEY']

    updater = Updater(token=BOT_KEY, use_context=True)
    dispatcher = updater.dispatcher
    # dispatcher.add_handler(CommandHandler('start', edna))
    dispatcher.add_handler(tevi_conversation_handler())

    updater.start_polling()
Exemple #21
0
# -*- coding: utf-8 -*-

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler
import configparser
import logging
from telegram import ChatAction

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.DEBUG)

config = configparser.ConfigParser()
config.read('bot.ini')


updater = Updater(token=config['BOT']['TOKEN'])
dispatcher = updater.dispatcher
help_text="""
[ x ] /invitelink  --> Prints the invite link to this group
[ x ] /twitter     --> Link to the ILUG-D Twitter
[ x ] /facebook    --> Facebook page of ILUG-D
[ x ] /mailinglist --> Link to the mailing list for ILUG-D
[ x ] /googlegroup --> Link to ILUG-D google groups
"""

def invitelink(bot, update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
    bot.sendMessage(chat_id=update.message.chat_id, text=config['BOT']['invite_link'])

def twitter(bot, update):
    bot.sendChatAction(chat_id=update.message.chat_id,
                       action=ChatAction.TYPING)
Exemple #22
0
import time

from telegram.ext import Updater
from telegram.ext import CommandHandler
from telegram.error import (TelegramError, Unauthorized, BadRequest, TimedOut,
                            ChatMigrated, NetworkError)

import urllib.request
from requests import ConnectionError
import requests
import urllib3
import io
import re

# running on telegram fridgobot
updater = Updater(token='TOKEN')
dispatcher = updater.dispatcher
jq = updater.job_queue

# user management
users = []


def start(bot, update):
    if update.message.chat_id not in users:
        users.append(update.message.chat_id)
        print(update.message.chat_id)
        bot.send_message(chat_id=update.message.chat_id,
                         text='- Feinsaubalarm abonniert -')

Exemple #23
0
    # Use all the SQL you like
    cur.execute("SELECT * FROM contend_conductor WHERE rut={}".format(ru))

    # print all the first cell of all the rows
    lista = []
    for row in cur.fetchall():
        lista.append(row)

    db.close()
    print(lista)
    for a in lista:
        update.message.reply_text(
            "Nombre:{} Rut:{}-{} Direccion: {} telefono: {}".format(
                a[1], a[3], a[4], a[6], a[7]))


all_conductor = llamar_db_nombres("contend_conductor")

updater = Updater('567147683:AAH06b2SV15KETB4hX1OJxePOGmBP21-vrE')
updater.dispatcher.add_handler(
    CommandHandler(["saludo", "saludar", "saludame", "hola", "holi", "hello"],
                   hello))
updater.dispatcher.add_handler(
    CommandHandler([
        "Muestrame todos los conductores", "Todos los conductores",
        "conductores"
    ], get_all_conductor))
updater.dispatcher.add_handler(CommandHandler(all_conductor, get_conductor))

updater.start_polling()
updater.idle()
Exemple #24
0
__author__ = 'alexsviridov'

# import telebot

BOT_TOKEN = "660361487:AAFBBtv8y1pfqY-pPekyT3Qbom9RMWD0Glg"

# Настройки
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import os

from DB import BotDatabase

#BOT_TOKEN = "TOKEN"
PORT = int(os.environ.get('PORT', '8443'))
updater = Updater(BOT_TOKEN)

dispatcher = updater.dispatcher

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


class CalcBot:
    Value = 0.0

    def __init__(self):
        self.db = BotDatabase()
        self.Value = self.db.getValue()
def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater(conf_handler.config['token'], use_context=True)

    #jq = updater.job_queue

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("status", status))
    dp.add_handler(CommandHandler("last", last))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("id", id))
    dp.add_handler(
        CommandHandler("monitor",
                       monitor,
                       pass_args=True,
                       pass_job_queue=True,
                       pass_chat_data=True))

    # whitelist conversations
    whiteListConv = ConversationHandler(
        entry_points=[CommandHandler('whitelist', whitelist)],
        states={
            wlUSERNAMEENTERED: [MessageHandler(Filters.text, usernameCheck)],
            wlUSERNAMECONFIRM: [
                MessageHandler(Filters.regex('^(Yes)$'), idEntry),
                MessageHandler(Filters.regex('^(No)$'), usernameEntry),
                MessageHandler(Filters.regex('^(Cancel)$'), cancelCommand),
                MessageHandler(Filters.text, useKeyboard)
            ],
            wlUSERNAMEEXISTS: [
                MessageHandler(Filters.regex('^(Yes)$'), usernameEntry),
                MessageHandler(Filters.regex('^(No)$'), cancelCommand),
                MessageHandler(Filters.text, useKeyboard)
            ],
            wlIDENTERED: [MessageHandler(Filters.text, idCheck)],
            wlIDCONFIRM: [
                MessageHandler(Filters.regex('^(Yes)$'), usernameAdd),
                MessageHandler(Filters.regex('^(No)$'), idEntry),
                MessageHandler(Filters.regex('^(Cancel)$'), cancelCommand),
                MessageHandler(Filters.text, useKeyboard)
            ],
            wlDELETECONFIRM: [
                MessageHandler(Filters.regex('^(Yes)$'), usernameDelete),
                MessageHandler(Filters.regex('^(No)$'), cancelCommand),
                MessageHandler(Filters.text, useKeyboard)
            ],
            wlDELETEENTERED:
            [MessageHandler(Filters.text, usernameDeleteCheck)]
        },
        fallbacks=[
            MessageHandler(
                Filters.regex(
                    re.compile('^(no|n|cancel|c|done)$', re.IGNORECASE)),
                cancelCommand)
        ])

    dp.add_handler(whiteListConv)

    # on noncommand i.e messages
    dp.add_handler(
        MessageHandler(Filters.regex(re.compile('(Emma)', re.IGNORECASE)),
                       emma))
    dp.add_handler(
        MessageHandler(Filters.regex(re.compile('(Judy)', re.IGNORECASE)),
                       judy))

    # any other conversational flotsam
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()
Exemple #26
0
from telegram.ext import Updater
from telegram import Poll, Bot, PollOption



updater = Updater(token='1022567655:AAGjqp1EcNQKQlFlzMIr6MpLQLIoi_YJ4YM', use_context=True)


text = open('third round/test.txt', "r", encoding="utf-8") '''this is the file that contains all the tweets'''

lines = text.readlines()


dispatcher = updater.dispatcher

import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                     level=logging.INFO)

def start(update, context):
    global lines
    context.bot.send_message(chat_id=update.effective_chat.id, text=lines[0])


import logging
from telegram.ext import CommandHandler
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

def instruction(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text='ጽሁፉ አዎንታዊ ከሆነ "1"ን አሉታዊ "2"ን ገለልትኛ ከሆነ "3" ይጻፉ')
Exemple #27
0
from telegram.ext import Updater, CommandHandler

token = Updater('1863100350:AAFG0pG-P86ZDv9BE7lCd1sNa4rnxHnNTU4',
                use_context=True)


def start(update, context):
    context.bot.send_message(
        text=
        'سلام به ربات Madrika خوش اومدی . \n برای اطلاعات بیشتر روی دستور /help   کلیک نمایید',
        chat_id=update.message.chat_id)


def website(update, context):
    context.bot.send_message(chat_id=update.message.chat_id,
                             text='وبسایت ما : n\ https://Madrika.com')


def help(update, context):
    context.bot.send_message(
        chat_id=update.message.chat_id,
        text=
        'برای دریافت ادرس وب سایت ما از دستور /website  استفاده کنید \n برای شروع مجدد ربات از /start  استفاده نمایید.'
    )


token.dispatcher.add_handler(CommandHandler('start', start))
token.dispatcher.add_handler(CommandHandler('website', website))
token.dispatcher.add_handler(CommandHandler('help', help))

token.start_polling()
    soup = bs(html, 'html.parser')
    days = soup.findAll('span', {'class': 'date-time'})
    temps = soup.select('#twc-scrollabe > table > tbody > tr > td.temp > div')

    total = ''
    for day, temp in zip(days, temps):
        update.message.reply_text(day.text + " :" + temp.text)

# help reply function
def help_command(bot, update) :
    update.message.reply_text("/help = what can I help? \n/weather = weather condition? ")
# weather condition function
def weather_command(bot, update) :
    update.message.reply_text("Type your zipcode: ")

updater = Updater(my_token)

#Filters.text는 텍스트에 대해 응답하며 이때 get_message 함수를 호출합니다.
#get_message 호출시 got text 와 받은 메세지를 답장합니다.
message_handler = MessageHandler(Filters.text, get_message)
updater.dispatcher.add_handler(message_handler)

help_handler = CommandHandler('help', help_command)
updater.dispatcher.add_handler(help_handler)

weather_handler = CommandHandler('weather', weather_command)
updater.dispatcher.add_handler(weather_handler)

photo_handler = MessageHandler(Filters.photo, get_photo)
updater.dispatcher.add_handler(photo_handler)
Exemple #29
0
from telegram.ext import Updater, InlineQueryHandler
from telegram import InlineQueryResultArticle, InputTextMessageContent
from distributor import *
from config import *
import logging

updater = Updater(token=config.get('token'), request_kwargs={
    'proxy_url': config.get('proxy'),
    'urllib3_proxy_kwargs': {
        'username': config.get('proxy_username'),
        'password': config.get('proxy_password')}})
d = Distributor()
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)


def light_callback(bot, update):
    query = update.inline_query.query
    if not query:
        return

    title, results = d.get_results(query)
    answers = list()
    all_results = title + '\n' + '\n'.join(map(lambda result: result[1], results))

    answers.append(
        InlineQueryResultArticle(
            id=len(results),
            title='share all sources',
            input_message_content=InputTextMessageContent(all_results),
            disable_web_page_preview=True,
            description=title))
Exemple #30
0
    try:
        # open the file
        txt = open(filename)

        # read the file: load each row in an element of the list without "/n"
        tasks_list = txt.read().splitlines()

        # close the file
        txt.close()

    except IOError:
        # File not found! We work with an empty list
        print("File not found!")
        exit()

    updater = Updater(token='590898204:AAGnj2CzA2VTOUFeeycawi6VRuWOeddxkyA')

    # add an handler to start the bot replying with the list of available commands
    dispatcher = updater.dispatcher
    dispatcher.add_handler(CommandHandler('start', start))

    # on non-command textual messages - echo the message on Telegram
    dispatcher.add_handler(MessageHandler(Filters.text, echo))

    # add an handler to insert a new task in the list
    newTask_handler = CommandHandler('newTask', new_task, pass_args=True)
    dispatcher.add_handler(newTask_handler)

    # add an handler to remove the first occurence of a specific task from the list
    removeTask_handler = CommandHandler('removeTask',
                                        remove_task,