import re from time import sleep import urllib import telebot bot = telebot.Telebot('1422038752:AAHIEkNVXQVgt7_05O3IWniuyLbwLCCoq0A') import requests as req url = 'https://www.youtube.com/results?' regexp = 'href=\"/watch\?v=(.{11})' pattern = re.compile(regexp) @bot.message_handler(content_types=['text']) def get(message): global url, regexp, pattern query_string = urllib.parse.urlencode({"search_query": message.text}) res = req.get(url + query_string) if res.ok: body = res.text links = pattern.findall(body)[:5] for link in links: answer = 'https://www.youtube.com/watch?v=' + link bot.send_message(message.from_user.id, answer) bot.polling(none_stop=True, interval=0)
## Если используем объект bot, значит его надо как-то объявить и инициализировать до этого ## для этого подключим модуль 'telebot' import telebot ## Здесь описать метод-конструктор для своего бота. Тут может быть ID, token, какие-либо параметры бота ## Подробнее - в документации по API! bot = telebot.Telebot() def get_text_messages(message): if message.text == "Привет": bot.send_message( "Привет, пользователь, если хочешь узнать, что я умею, напиши: /help " ) elif message.text == "/help": bot.send_message("Напиши привет!") else: bot.send_message("Я тебя не понимаю. Напиши /help.") def get_name(message): name = message.text bot.send_message('Приятно познакомиться, ' + name + '!') def start(message): ## Проверяем поступил ли текст if message.text: if message.text == '/reg': bot.send_message("Как тебя зовут?")
def main(): # will Create the Updater and pass it our bot's token. # Make sure to set use_context=True to use the new context based callbacks updater = Updater( os.getenv("TELEGRAM_TOKEN",""), use_context=True) bot = telebot.Telebot(os.getenv("TELEGRAM_TOKEN")) @bot.message_handler(commands=['info']) # Get the dispatcher to register handlers dp = updater.dispatcher # Add conversation handler with the states INFO, LOCATION, BIO, CLASSNAMES conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ CITY: [MessageHandler(Filters.text, city)], PINCODE: [MessageHandler(Filters.text, pincode)], REQ: [MessageHandler(Filters.text, req)], STANDARD: [MessageHandler(Filters.text, standard)], BOARD: [MessageHandler(Filters.text, board)], MEDIUM: [MessageHandler(Filters.text, medium)], SUBJECTS: [MessageHandler(Filters.text, subjects)], CONTACT: [MessageHandler(Filters.text, contact)], EMAIL: [MessageHandler(Filters.text, email)], CONFIRM: [MessageHandler(Filters.text, confirm)], END: [MessageHandler(Filters.text, end)] }, fallbacks=[CommandHandler('cancel', cancel)], ) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # press ctrl c for stopping the bot # SIGTERM or SIGABRT. This should be used most of the time # start_polling() is non-blocking and will stop the bot. updater.idle()
def get_user_step (uid): if uid in userStep: return userStep [uid] else knownUsers.append (uid) userStep [uid] = 0 print (color.RED + "[i] ¡Nuevo Usuario!" + color.ENDC) #listener def listener (messages): for m in messages if m.content_type == 'text' print ("[" + str (m.chat.id) + "]" + str (m. chat.first_name) + ": " + m.text) bot = telebot.Telebot (TOKEN) bot.set_update_listener (listener) #diccionario con comandos bot commands = { 'start' : 'Arranca el bot' 'ayuda' : 'Comandos disponibles' 'exec' : 'Ejecuta un comando' } #ayuda @bot.message_handler (commands = ['ayuda']) def.command_help (m): cid = m.chat.id help_text = "Comandos disponibles: \n" for key in commands:
import telebot import config import random bot = telebot.Telebot(config.TOKEN) @bot.message_handler(commands=['start']) def welcome (message): sti = open('sticker/AnimatedSticker.webp', 'rb') bot.send_sticker(message.chat.id, sti) #клавиша markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.ReplyKeyboardButton("Рандомное число") item2 = types.ReplyKeyboardButton("Как делишки?:)") markup.add(item1, item2) bot.send_message(message.chat.id, "Привет, {0.first_name}|\nЯ создан - {1.first_name}</b>, чтобы поболтать.".format(message.from_user, bot.get_me()),) parse_mode='html', reply_markup=markup @bot.message_handler(content_types=['text']) def lal(message): if message.chat.type == 'private': if message.text == 'Рандомное число': bot.send_message(message.shat.id, str(random.randint(0,100))) elif message.text == 'Как делишки?:)': markup = types.InlineKeyboardMarkup(row_width=2) item1 = types.InlineKeyboardButton("Хорошо", callback_data='good')
import telebot bot = telebot.Telebot("1244021573:AAEakjjhchvuB7RPQ5-fEZ46w46GcSsNS88") @bot.message.handler(content_types=["text"]) def repeat_all_messages(message): bot.send_message(message.chat.id, message.text) if __name__ == '__main__': bot.polling(nonstop=true)
import telebot from settings.settings import token, apiHash, apiToken, admins, botApiUrl import functions.functions as func import json import requests import time bot = telebot.Telebot(token) bot.remove_webhook() with open('database/ads.json') as file: adsList = json.load(file) def main(): try: url = 'https://jdbiz.ru' html = func.getHtml(url) func.checkRepeat(adsList, func.getAds(html), admins, botApiUrl, bot) time.sleep(60) except Exception as e: print(e, 2) main() if __name__ == '__main__': while True: main()
""" import requests from bs4 import BeautifulSoup import pandas as pd import random import telebot from telebot import types # VARIABLES url = 'https://covid-2019.es/provincias' nombre_tabla = 'table' bot = telebot.Telebot('token') # FUNCIONES def extraer_tabla_web(url, nombre_tabla): pagina = requests.get(url).text soup = BeautifulSoup(pagina, 'lxml') tabla = soup.find('table', attrs={'id': nombre_tabla}) listas = {i: [] for i in range(5)} i = 0
import telebot bot = telebot.Telebot(token='your_token_here') ##sayhi bot while typing /start @bot_message_handler(commands=['start']) def bot_sayhi(message): bot.reply_to(message, "hello !") ## custom text input @bot_message_handler(func=lambda message: True) def say_bot(message): custom_message = message.text if custom_message == 'hello there': bot.reply_to(message, "hello there you are !") else: bot.reply_to(message, "still searching !") print('bot is running!') bot.polling() """ >>bot is running! """
import config import telebot bot = telebot.Telebot(config.token) @bot.message_handler(content_types=["text"]) def repeat_all_messages(message): bot.send_message(message.chat.id, messaage.text) if __name__ == '__main__': bot.polling(none_stop=true) python3 bot.py
import telebot from telebot import types import COVID19Py covid19 = COVID19Py.COVID19() bot = telebot.Telebot("1148569083:AAH5QVB2oWda-SUPgup01CjMGabjnUaFcC0") @bot.message_handler(commands=['start']) def start(message): send_mess = f'<b>Привет {message.from_user.first_name}!</b>\nВведите страну' bot.send_message(message.chat, id, send_mess, parse_mode='html') bot.polling(none_stop=True) #latest = covid19.getLatest() #location = covid19.getLocationByCountryCode('US') print(latest, location)
import telebot bot = telebot.Telebot('1079190137:AAFcTWcmKiTPEmAUowbL1pdN3jw1YzSUrFY') @bot.message_handler(commands=['start']) def start_message(message): bot.send_message(message.chat.id, 'Привет, ты yсал мне /start') bot.polling()