Beispiel #1
0
def bot_runner(thread_statuses, q_offer, bot_settings_file, bot_configs_dir):
    """ Function creates a Telegram Bot and supplies it with offers from q_offer queue.
    :param thread_statuses: used for debugging and checking up on threads
    :param q_offer: offers which are supplied to the bot
    :param bot_settings_file: settings file path
    :param bot_configs_dir: configs directory path
    """
    # Starting the bot
    thread_statuses[current_thread().name] = "Booting"
    try:
        bot = TelegramBot(bot_settings_file, bot_configs_dir)
    except Exception as err:
        thread_statuses[current_thread().name] = "Error -- %s" % err.__str__()
        return
    bot.start()

    while not current_thread().is_stopped():
        thread_statuses[current_thread().name] = "Waiting"

        while q_offer.qsize() > 0:
            # Get an offer and update status
            thread_statuses[current_thread().name] = "Work %02d" % q_offer.qsize()
            offer = q_offer.get()

            # Process the offer (and send it if that's needed
            bot.process_offer(offer)

    bot.stop()
    thread_statuses[current_thread().name] = "Stopped"
Beispiel #2
0
	def initBot(self):
		botRequest = None
		if self.CONFIG['bot']['proxy'] is not None:
			botRequest = telegram.utils.request.Request(
				con_pool_size = 10,
				proxy_url=self.CONFIG['bot']['proxy'],
				connect_timeout=120, read_timeout=1200)
		self.bot = TelegramBot(self.CONFIG['bot']['token'], botRequest=botRequest)
Beispiel #3
0
def main():
    configparser.read(sys.argv[1])
    init_logger(configparser)
    bot = TelegramBot(configparser, logger)
    bot.message_loop()
    logger.info("Bot " + bot.getMe()['first_name'] + " started")
    # Keep the program running.
    while 1:
        time.sleep(10)
Beispiel #4
0
import os
import requests
from bottle import Bottle, response, request as bottle_request
from bot import TelegramBot

if __name__ == '__main__':
    app = TelegramBot()
    app.run(host="localhost", port="5000")  ## Used for running locally
    # app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000))) ## used for running on Heroku
Beispiel #5
0
app.config.from_envvar("CONFIG_FILE")

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

if app.config.get('LOG_FILE', None):
    handler = logging.FileHandler(app.config['LOG_FILE'])
else:
    handler = logging.StreamHandler(stream=sys.stdout)

handler.setFormatter(formatter)
logger.addHandler(handler)
app.logger.addHandler(handler)

bot = TelegramBot(app.config['TOKEN'])

logger.propagate = False


@app.route("/test")
def index():
    return "it's working, it's workiiiiing"


@app.route('/', methods=['POST'])
def webhook():
    update = request.get_json()
    bot.process_update(update)
    return 'ok'
Beispiel #6
0
from time import time, sleep

from generator import Generator
from bot import TelegramBot

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

generator = Generator()

tokens = {}
with open('config.json') as c:
    j = json.load(c)
    tokens = j['tokens']

bots = {}

for u in generator.users:
    start = time()
    print 'Initializing %s bot' % u
    bots[u] = TelegramBot(tokens[u])
    print 'Bot initialized (%.2f s)' % float(time() - start)

for i in range(10):
    (msg, diff, user) = generator.getMessage()
    print 'Next message in %d seconds' % diff
    sleep(diff)
    b = bots[user]
    b.sendMessage(msg)
Beispiel #7
0
from bot import TelegramBot
from random import randint

bot_ob = TelegramBot("config.cfg")


def check_message_contents(msg):
    """
    Determines if the message variable is correct response
    :param msg:
    :return: String var ok or Prompt response
    """
    if msg == "y" or msg == "n":
        return 'ok'
    else:
        return 'Response needs to be either "y" or "n"'


def generate_img(all_content_list):
    """
    Generate a random number between 1 - 616196 and append to url to get frame
    :return: String var URL to get frame of video
    """
    frame_rand = randint(1, 61696)
    # keep looping until frame_rand is not in all_content_list
    while frame_rand in all_content_list:
        frame_rand = randint(1, 61696)
    url = 'https://framex-dev.wadrid.net/api/video/Falcon%20Heavy%20Test%20Flight%20(' \
          'Hosted%20Webcast)-wbSwFU6tY1c/frame/' + str(frame_rand)
    return url, frame_rand
Beispiel #8
0
from bot import TelegramBot
import yaml

with open("config/config.yml", 'r') as ymlfile:
    cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)

bot = TelegramBot(cfg['token'])
bot.start()
bot.stop()
import time
import signal
from threading import Thread
import threading
import pathFinder
from bot import TelegramBot
import sys
import os

# Fix pathing issues with Windows
sys.path.insert(1, '../SchoolPathFinder')

bot = TelegramBot()


def exit_gracefully(signum, frame):
    # restore the original signal handler as otherwise evil things will happen
    # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant
    signal.signal(signal.SIGINT, original_sigint)

    # restore the exit gracefully handler here
    sys.exit()


def UpdateQueuePosition(bot, one, chat_id=None, item=None):
    """This function will send a message to the user telling him what his position in the queue is

    Args:
        bot (TelegramBot): Please refer to bot.py
        one (bool): If send to only one user
        chat_id (int, optional): Chat id of user to send to. Defaults to None.
Beispiel #10
0
def index():
    res = request.get_json()
    robot = TelegramBot()
    robot.parseData(res)
    isSuccessful = robot.conditionalResponse()
    return jsonify(success=isSuccessful)
Beispiel #11
0
from bot import TelegramBot

bot = TelegramBot("config.cfg")


def make_reply(msg):
    reply = None
    if msg is not None:
        reply = 'Okay'
    return reply

update_id = None
while True:
    updates = bot.get_updates(offset=update_id)
    updates = updates["result"]
    if updates:
        for item in updates:
            update_id = item["update_id"]
            try:
                message = str(item["message"]["text"])
            except:
                message = None
            from_ = item["message"]["from"]["id"]
            reply = make_reply(message)
            bot.send_message(reply, from_)
Beispiel #12
0
        ssl_context.load_verify_locations(SCANNER["cert_file"])
        ssl_context.check_hostname = False

        subnet_filters = SCANNER.get("subnets", None)

        scanner = RouterOsScanner(INTERVAL, SCANNER['address'],
                                  SCANNER["username"], SCANNER["password"],
                                  ssl_context, subnet_filters)
    else:
        raise ValueError(
            "Unknown scanner type. Should be one of ['arping', 'routeros_api']"
        )

    scanner.set_new_device_alert(new_device_alert)

    bot = TelegramBot(TOKEN, BotMainState)
    bot.allow_chat(ADMIN_CHAT)

    print("Starting bot...")
    bot.start()
    print("Bot started")

    print("Starting scanner...")
    scanner.start()
    print("Scanner started")

    try:
        while True:
            sleep(300)
    except KeyboardInterrupt as e:
        print("Interrupted")
Beispiel #13
0
handler.setFormatter(logFormatter)
logger = logging.getLogger('Logger')
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info('Start main')

logger.info('Load config')
config = configparser.ConfigParser()
config.read('motion-sensor.ini')

pool = multiprocessing.Pool(processes=3)
m = multiprocessing.Manager()
camQueue = m.Queue()
botQueue = m.Queue()

logger.info('Init cam')
cam = CamThread(3, "Camera", config, logger, camQueue, botQueue)
cam.start()

logger.info('Init motion sensor')
pirThread = PirThread(1, "PirThread", config, logger)
pirThread.start()

logger.info('Init bot')
telegramBot = TelegramBot(1, "Bot", config, logger, pirThread, cam, botQueue)
telegramBot.start()
cam.addBot(telegramBot)
pirThread.addBot(telegramBot)

logger.info('Init complete')
Beispiel #14
0
from config import Config

from yandex_webhook import YandexWebhook
from alice_handler import AliceHandler

app = Flask(__name__)

config = Config()

via_webhook = True

if via_webhook is False:
	# для телеграм бота
	from bot import TelegramBot

	telegram_bot = TelegramBot(token=config.telegtam_token, via_polling=True)
	telegram_dispatcher = telegram_bot.get_dispatcher()
else:
	# для вебхуков Алисы
	from plugins import animego
	from plugins import mal
	from cast import Cast
	from mal2alice import Mal2Alice
	import time
	site = animego.Site()
	print('Caching mal...')
	mal2alice = Mal2Alice(mal, site)
	print('Finding chromecasts...')
	cast = Cast()

Beispiel #15
0
import datetime
import logging
import os

import mpd
import redis
import requests

from bot import TelegramBot

TOKEN = os.environ.get("TELEGRAM_TOKEN")
bot = TelegramBot(TOKEN)

MPD_PASSWORD = os.environ.get("MPD_PASSWORD")
MPD_HOST = os.environ.get("MPD_HOST", "localhost")
MPD_PORT = os.environ.get("MPD_POST", 6600)

YEELIGHT_BASE_URL = os.environ.get("YEELIGHT_BASE_URL")

redisconn = redis.Redis()


def time_format(timestamp):
    dt = datetime.datetime.fromtimestamp(timestamp)
    return dt.strftime('%Y-%m-%d %H:%M:%S')


def get_mpd_client():
    mpd_client = mpd.MPDClient()
    mpd_client.connect(MPD_HOST, MPD_PORT)
    if MPD_PASSWORD:
Beispiel #16
0
from config import Config
from bot import TelegramBot
from time import sleep

BOT_URL = "https://api.telegram.org/bot"
TOKEN = Config.ASKME_BOT_TOKEN

new_bot = TelegramBot(BOT_URL, TOKEN)


def main():
    while True:
        answer = new_bot.get_message()
        if answer is not None:
            chat_id = answer["chat_id"]
            text = answer["text"]
            if text == "/start":
                print(new_bot.send_message(chat_id, "Hello, i'm AskMeBot"))
            elif text == "hi":
                print(new_bot.send_message(chat_id, text))
            else:
                print(new_bot.send_message(chat_id, "How can i help you!"))
        else:
            continue
            sleep(3)


if __name__ == "__main__":
    main()
Beispiel #17
0
def main():
    TelegramBot('####:####')