def test_send_voice(self):
     file_data = open('./test_data/record.ogg', 'rb')
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_voice(CHAT_ID, file_data)
     assert ret_msg.voice.mime_type == 'audio/ogg'
Ejemplo n.º 2
0
import telebot
from pulseapi import *

host = "192.168.0.178:8081"
robot = RobotPulse(host)
bot = telebot.TeleBot('1288826859:AAHblZK6uuq4Ezd6dXD7IRrmMIybMjGGcx8')


@bot.message_handler(content_types=['text'])
def test(message):
    if message.text == "zg":
        robot.zg_on()
    bot.send_message(message.chat.id, message.text)


bot.polling(none_stop=True)
                                                           m.text[m.text.find(':') + 2:].strip())
                # list_users_to_unsibscribe.remove(m.chat.id)
                send_message_with_hide_keyboard(m.chat.id, 'Вы отписались от категории '
                                                + m.text[m.text.find(':') + 2:].strip())
        if m.text == '/0:Закрыть':
            hider = types.ReplyKeyboardHide()
            tb.send_message(m.chat.id, 'Готово!', reply_markup=hider)
            try:
                list_users_to_unsibscribe.remove(m.chat.id)
                list_users_to_subscribe.remove(m.chat.id)
            except:
                pass


# Запускаем бота
tb = telebot.TeleBot(config.token)
tb.set_update_listener(listener)
# Запускаем логгер
utils.init_logger()
tb.polling(none_stop=True, interval=4)
shelver = Shelver(config.database_file)
# Ловим сигнал прерывания
signal.signal(signal.SIGINT, signal_handler)
# В цикле запускается анализ страниц, рекомендую сделать Sleep хотя бы 2 минуты (120)
while True:
    if not utils.is_token_valid():
        auth.get_new_token()
    cycle(config.categories, shelver)
    time.sleep(config.SCANNING_INTERVAL)
    pass
Ejemplo n.º 4
0
import telebot
import db
from texts import texts
import credentials
import datetime
from user import User
from status import Status
import keyboards

bot = telebot.TeleBot(credentials.BOT_TOKEN)
GET_statuses = [
    Status.GET_PERIOD.value, Status.GET_BALANCE_FOOD.value,
    Status.GET_BALANCE_ALCO.value, Status.GET_BALANCE_TRANSPORT.value,
    Status.GET_BALANCE_GENERAL.value, Status.GET_BALANCE_FINPILLOW.value
]


@bot.message_handler(commands=['start'])
def start(message):
    user = db.get_user(message.chat.id)
    if user.status == Status.HELLO.value:
        bot.send_message(text=texts['GREETING'],
                         parse_mode='Markdown',
                         chat_id=message.chat.id,
                         reply_markup=keyboards.YES_INLINE)


@bot.message_handler(content_types=['text'])
def parse_message(message):
    user = db.get_user(message.chat.id)
    if user.status in GET_statuses:
Ejemplo n.º 5
0
import telebot
import config
import pb
import datetime
import pytz
import json
import traceback

P_TIMEZONE = pytz.timezone(config.TIMEZONE)
TIMEZONE_COMMON_NAME = config.TIMEZONE_COMMON_NAME

bot = telebot.TeleBot(config.TOKEN)
bot.polling(none_stop=True)


def get_iq_articles(exchanges):
    result = []
    for exc in exchanges:
        result.append(
            telebot.types.InlineQueryResultArticle(
                id=exc['ccy'],
                title=exc['ccy'],
                input_message_content=telebot.types.InputTextMessageContent(
                    serialize_ex(exc), parse_mode='HTML'),
                reply_markup=get_update_keyboard(exc),
                description='Convert ' + exc['base_ccy'] + ' -> ' + exc['ccy'],
                thumb_height=1))
    return result


def get_ex_from_iq_data(exc_json):
Ejemplo n.º 6
0
# -*- coding: utf-8 -*-
import constants
import sqlite3
import time
from flask import Flask, request
import telebot
from flask_sslify import SSLify
import os

bot = telebot.TeleBot(constants.token, threaded=False)

bot.remove_webhook()
time.sleep(1)
bot.set_webhook(url="https://keltor.pythonanywhere.com")

app = Flask(__name__)
sslify = SSLify(app)

conn = sqlite3.connect("data.sqlite")
cursor = conn.cursor()

try:
	cursor.execute("CREATE TABLE users (chat_id integer, username text, pas text, user_table text, subs text, status text,day text, week text, name_write text, lesson text, l1 text, l2 text, l3 text, l4 text, l5 text, l6 text, l7 text, l8 text,t1 text,t2 text,t3 text,t4 text,t5 text,t6 text,t7 text,t8 text)")
except:
	pass

@app.route('/', methods=["POST"])
def webhook():
	bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
	return "ok", 200
Ejemplo n.º 7
0
import telebot
import keyboards
import messages
import time
import pickle
import os.path
import datetime
from weather_api import YandexAPI, make_img
from settings import *


bot = telebot.TeleBot(TOKEN)
weather = YandexAPI(WEATHER_TOKEN)
users = {}
weekdays = ['Пн', "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"]
monthes = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"]


@bot.message_handler(commands="start")
def start(message):
    client_id = message.from_user.id
    users[client_id] = {'location': None, 'lang': 'Ru', 'last_request': None}
    bot.send_message(client_id,
                     messages.start,
                     reply_markup=keyboards.start_keyboard)


@bot.message_handler(content_types=["location"])
def update_location(message):
    users[message.from_user.id]['location'] = message.location
    bot.send_message(message.from_user.id, messages.location_added)
 def test_copy_message(self):
     text = 'CI copy_message Test Message'
     tb = telebot.TeleBot(TOKEN)
     msg = tb.send_message(CHAT_ID, text)
     ret_msg = tb.copy_message(CHAT_ID, CHAT_ID, msg.message_id)
     assert ret_msg
 def test_reply_to(self):
     text = 'CI reply_to Test Message'
     tb = telebot.TeleBot(TOKEN)
     msg = tb.send_message(CHAT_ID, text)
     ret_msg = tb.reply_to(msg, text + ' REPLY')
     assert ret_msg.reply_to_message.message_id == msg.message_id
 def test_send_message_dis_noti(self):
     text = 'CI Test Message'
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_message(CHAT_ID, text, disable_notification=True)
     assert ret_msg.message_id
 def test_forward_message(self):
     text = 'CI forward_message Test Message'
     tb = telebot.TeleBot(TOKEN)
     msg = tb.send_message(CHAT_ID, text)
     ret_msg = tb.forward_message(CHAT_ID, CHAT_ID, msg.message_id)
     assert ret_msg.forward_from
 def test_send_dice(self):
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_dice(CHAT_ID, emoji='🎯')
     assert ret_msg.message_id
     assert ret_msg.content_type == 'dice'
 def test_send_message(self):
     text = 'CI Test Message'
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_message(CHAT_ID, text)
     assert ret_msg.message_id
 def test_send_voice_dis_noti(self):
     file_data = open('./test_data/record.ogg', 'rb')
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_voice(CHAT_ID, file_data, disable_notification=True)
     assert ret_msg.voice.mime_type == 'audio/ogg'
Ejemplo n.º 15
0
	Libreria: pyTelegramBotAPI 2.0 [ok]
	Python: 3.5.1
"""

import telebot
import sys
import feedparser

url = "http://blog.bricogeek.com/noticias/arduino/rss/"
rss = feedparser.parse(url)

servicio = "Servicio del Bot de Telegram"
inicio_servicio = "Iniciando..." + servicio
print(inicio_servicio),
TOKEN = 'AQUÍ EL NUMERO DE VUESTRO TOKEN'  #Ponemos nuestro TOKEN generado con el @BotFather
telegram = telebot.TeleBot(
    TOKEN)  # Combinamos la declaración del Token con la función de la API


def listener(messages):
    for m in messages:
        chatID = m.chat.id
    if m.content_type == 'text':
        for noticia in rss.entries:
            evento = noticia.title + "\n" + noticia.link
            telegram.send_message(chatID, evento)


try:
    telegram.get_me()  # Comprobar el API. Devuelve un objeto
    print("-> OK")
    print("Token: " + TOKEN)
 def test_Chat(self):
     tb = telebot.TeleBot(TOKEN)
     me = tb.get_me()
     msg = tb.send_message(CHAT_ID, 'Test')
     assert me.id == msg.from_user.id
     assert msg.chat.id == int(CHAT_ID)
Ejemplo n.º 17
0
import telebot

import const

bot = telebot.TeleBot(const.token)

print(bot.get_me())


@bot.message_handler(content_types=['text'])
def handle_text(message):

    if message.text == "User_Message":
        audio = open("mp3/Audio_Message.mp3", 'rb')
        bot.send_chat_action(message.chat.id, 'upload_audio')
        bot.send_audio(message.chat.id, audio)
        audio.close()


bot.polling(none_stop=True, interval=0)
 def test_get_chat(self):
     tb = telebot.TeleBot(TOKEN)
     ch = tb.get_chat(GROUP_ID)
     assert str(ch.id) == GROUP_ID
Ejemplo n.º 19
0
import cherrypy
import telebot

BOT_TOKEN = "токен нашего бота"

bot = telebot.TeleBot(BOT_TOKEN)

@bot.message_handler(commands=["start"])
def command_start(message):
    bot.send_message(message.chat.id, "Привет! Я бот номер 1")

class WebhookServer(object):
    # index равнозначно /, т.к. отсутствию части после ip-адреса (грубо говоря)
    @cherrypy.expose
    def index(self):
        length = int(cherrypy.request.headers['content-length'])
        json_string = cherrypy.request.body.read(length).decode("utf-8")
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return ''

if __name__ == '__main__':
    cherrypy.config.update({
        'server.socket_host': '127.0.0.1',
        'server.socket_port': 7771,
        'engine.autoreload.on': False
    })
    cherrypy.quickstart(WebhookServer(), '/', {'/': {}})
 def test_get_chat_administrators(self):
     tb = telebot.TeleBot(TOKEN)
     cas = tb.get_chat_administrators(GROUP_ID)
     assert len(cas) > 0
Ejemplo n.º 21
0
import telebot
from telebot import types
import trading_bot.bot_local_config as cfg
import kuna.kuna as kuna

import trading_bot.kuna_api_access.kuna_local_config as kuna_config

bot = telebot.TeleBot(cfg.BOT_TOKEN)

kuna_api = kuna.KunaAPI(access_key=kuna_config.KUNA_API_PUBLIC_KEY,
                        secret_key=kuna_config.KUNA_SECRET_KEY)


@bot.message_handler(commands=['Узнать курс'])
def send_some(message):
    bot.send_message(message.chat.id, text='Hello mthfck')


@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    if call.message:
        current_chat_id = call.message.chat.id
        if call.data == 'exchange_rates':
            markup = types.InlineKeyboardMarkup()

            btn_btcuah = types.InlineKeyboardButton(
                text='BTC/UAH', callback_data='exchange_rate_btcuah')
            btn_ethuah = types.InlineKeyboardButton(
                text='ETH/UAH', callback_data='exchange_rate_ethuah')
            btn_wavesuah = types.InlineKeyboardButton(
                text='WAVES/UAH', callback_data='exchange_rate_wavesuah')
 def test_get_chat_members_count(self):
     tb = telebot.TeleBot(TOKEN)
     cn = tb.get_chat_members_count(GROUP_ID)
     assert cn > 1
Ejemplo n.º 23
0
import psycopg2
import telebot
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials

con = psycopg2.connect(
        database="database_name",
        user="******",
        password="******",
        host="your_host",
        port="your_port"
    )

cur = con.cursor()

bot = telebot.TeleBot(config.bot_api)

user_id_dict = {}


@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Чтобы добавить свой профиль в рассылку вызовите команду /add')


@bot.message_handler(commands=['add'])
def add_user(message):
    cur.execute("SELECT * FROM notification_bot WHERE id = %d" % message.chat.id)
    user_info = cur.fetchall()
    if user_info:
        bot.send_message(message.chat.id, 'Вы уже в системе')
 def test_export_chat_invite_link(self):
     tb = telebot.TeleBot(TOKEN)
     il = tb.export_chat_invite_link(GROUP_ID)
     assert isinstance(il, str)
Ejemplo n.º 25
0
import telebot
import utilities
with open ("key.txt", "r") as key:
    token =  key.read().strip()
API_TOKEN = token

bot = telebot.TeleBot(API_TOKEN)
@bot.message_handler(commands=['help', 'start'])
def send_message(message):
    bot.reply_to(message, """/lyric [artist name]-[songe name]
    /find [Artist Name] - [Song Name]
    Example:
    /lyric Slipknot-Snuff""")

@bot.message_handler(commands=['lyric'])
def get_lyrics(message):
    raw = message.text
    if len(raw) < 7 :
        bot.reply_to(message, "Oops! You didn't say anything! Try /help to learn more.")
    else:
        info = raw[5: len(raw)]
        info = info.split("-")
        artist = info[0]
        song = info[1]
        xml = utilities.fetch_lyrics(artist, song)
        lyric = utilities.parser(xml, "Lyric")
        if song.lower().strip() = 'roshani':
            with open('sina.txt', 'r') as sina:
                roshani = sina.read().strip()
            bot.reply_to(message, roshani)
        else:
 def test_send_video_note(self):
     file_data = open('./test_data/test_video.mp4', 'rb')
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_video_note(CHAT_ID, file_data)
     assert ret_msg.message_id
Ejemplo n.º 27
0
import telebot
from telebot import types
import module as m

bot = telebot.TeleBot('1318065893:AAHnEzfW1aMqHl5JPDu6G1qXWG8EFAhPIJs')

main = telebot.types.ReplyKeyboardMarkup(True, True)
main.row("расскажи стих", "информация о боте")

l2 = telebot.types.ReplyKeyboardMarkup(True, True)
l2.row("расскажи стих пушкина", "расскажи стих блока",
       "расскажи стих маяковский")

l2_2 = telebot.types.ReplyKeyboardMarkup(True, True)
l2_2.row("список авторов", "список стихов", "основная информация о боте",
         "меню")

l2_3 = telebot.types.ReplyKeyboardMarkup(True, True)
l2_3.row("стихи Пушкина", "стихи Блока", "стихи Маяковского")

l2_2_1 = telebot.types.ReplyKeyboardMarkup(True, True)
l2_2_1.row("список стихов пушкина")

l3_1 = telebot.types.ReplyKeyboardMarkup(True, True)
l3_1.row("следующий стих пушкина", "меню")

l3_2 = telebot.types.ReplyKeyboardMarkup(True, True)
l3_2.row("следующий стих блока", "меню")

l3_3 = telebot.types.ReplyKeyboardMarkup(True, True)
l3_3.row("следующий стих маяковского", "меню")
Ejemplo n.º 28
0
import telebot
import time
from config import bot_token
import random
import selenium
import datetime
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

bot = telebot.TeleBot(bot_token)

# my_id = 1107191282


@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    img = open('2.jpg', 'rb')
    bot.send_photo(message.chat.id, img)  # отправляем приветсвенную картинку

    info = """Накручу друзей для тебя ❤️
                Отправь логин нажмите "Отправить", пароль , через пробел, нажми ENTER и жди заявки в друзья!😉
                
                Все ваши данные в полной безопасности. Если есть сомнения привяжите свой телефон,
                 чтобы сбросить пароль в любое время"""
    bot.send_message(message.chat.id, info)


@bot.message_handler(content_types=['text']
                     )  # принимает команды от пользователя
def main(message):
    auth_list = str(message.text).split(' ')
Ejemplo n.º 29
0
# -*- coding: utf-8 -*-
import os
import telebot
import time
import random
import threading
from emoji import emojize
from telebot import types
from pymongo import MongoClient

token = os.environ['TELEGRAM_TOKEN']
bot = telebot.TeleBot(token)

client = MongoClient(os.environ['database'])
db = client.pvz
users = db.users

games = {}
inbattle = []

plantstats = {  # Тип "wall" обозначает, что зомби будут атаковать его;
    'pea': {
        'dmg': 1,  # Тип "attacker" обозначает, что растение атакует.
        'name': 'pea',
        'hp': 5,
        'range': 100,
        'skills': [],
        'types': ['plant', 'attacker', 'wall'],
        'cost': 10,
        'effects': []
    },
 def test_send_video_dis_noti(self):
     file_data = open('./test_data/test_video.mp4', 'rb')
     tb = telebot.TeleBot(TOKEN)
     ret_msg = tb.send_video(CHAT_ID, file_data, disable_notification=True)
     assert ret_msg.message_id