i = "123"
with open("data.txt", 'w') as f:
out_file.write(str(i))
####
with open("data.txt") as f:
i = f.readlines()[0]
data = {
"name" : "RimMirK",
"id" : 148734,
"interval" : 3.5,
"is_answer" : True,
"message" : {
"lines" : [
"hello!",
"I'm RimMirK"
],
"id" : 136,
}
}
def get_post(message):
m = bot.send_message(message.chat.id, 'Пришли пост. Для остановки введите `стоп`', parse_mode="markdown")
bot.register_next_step_handler(m, posts)
def posts(message):
if message.text != "стоп":
posts.append(message.id)
get_post(message)
else:
# код / вызов_функции() обработки
C:\Users\User>py
Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> text = '123'
>>> print('hello') if command in text for command in ["привет", "хай"]
File "<stdin>", line 1
print('hello') if command in text for command in ["привет", "хай"]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: expected 'else' after 'if' expression
>>> print('hello') if command in text else pass for command in ["привет", "хай"]
File "<stdin>", line 1
print('hello') if command in text else pass for command in ["привет", "хай"]
^^^^
SyntaxError: invalid syntax
>>> print('hello') if command in text else ... for command in ["привет", "хай"]
File "<stdin>", line 1
print('hello') if command in text else ... for command in ["привет", "хай"]
^^^
SyntaxError: invalid syntax
>>> print('hello') if command in text else print('',end='') for command in ["привет", "хай"]
File "<stdin>", line 1
print('hello') if command in text else print('',end='') for command in ["привет", "хай"]
^^^
SyntaxError: invalid syntax
>>> command print('hello') if command in text else print('',end='') for command in ["привет", "хай"]
File "<stdin>", line 1
command print('hello') if command in text else print('',end='') for command in ["привет", "хай"]
^^^^^
SyntaxError: invalid syntax
>>> print('hello') if command in text else print('',end='') command for command in ["привет", "хай"]
File "<stdin>", line 1
print('hello') if command in text else print('',end='') command for command in ["привет", "хай"]
^^^^^^^
SyntaxError: invalid syntax
>>> print('hello') if command in text else print('',end='') for command in ["привет", "хай"]
File "<stdin>", line 1
print('hello') if command in text else print('',end='') for command in ["привет", "хай"]
^^^
SyntaxError: invalid syntax
# Импорты
import telebot
from telebot import types
import os
# Определение бота
bot = telebot.TeleBot("TOKEN", parse_mode="MARKDOWN")
bot.set_webhook()
# Убирание кнопок
none = telebot.types.ReplyKeyboardRemove()
# # # # # # # # # # # # # # # # # # # # # # # # # # #
# команда /start
@bot.message_handler(commands=['start'])
def start(message):
buttons = types.InlineKeyboardMarkup()
books = [book.replace('_', ' ') for book in os.listdir('books')]
for book in books:
buttons.add(types.InlineKeyboardButton(f"{book}", callback_data=f"-book-{book}"))
bot.send_message(message.chat.id, f"Выбери учебник", reply_markup=buttons)
# Обработчик callback
@bot.callback_query_handler(func=lambda c: True)
def callback(c):
if '-book-' in c.data:
book = c.data.split('-book-', maxsplit=1)[1]
exercises = os.listdir(f"books\{book.replace(' ', '_')}")
buttons = types.InlineKeyboardMarkup()
btns = []
for exercise in exercises:
btns.append(
types.InlineKeyboardButton(
f"{exercise.replace('.png','')}",
callback_data=fr"-send-{book.replace(' ', '_')}\{exercise}"
)
)
for i in range(0, len(btns), 3):
try: buttons.add(btns[i], btns[i+1], btns[i+2])
except:
try: buttons.add(btns[i], btns[i+1])
except:
try: buttons.add(btns[i])
except: pass
bot.send_message(c.message.chat.id, f"Выбери номер", reply_markup=buttons)
if '-send-' in c.data:
path = f"books\{c.data.split('-send-', maxsplit=1)[1]}"
bot.send_photo(c.message.chat.id, photo=open(path,'rb'))
bot.polling(none_stop=True)
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: file must be non-empty
- файл пустойtelegram.error.BadRequest: Button_data_invalid
)@dp.message_handler()
async def echo(message: types.Message):
# code
@bot.message_handler(func=lambda message: True)
def sayanswer(message):
kb = types.InlineKeyboardMarkup(row_width=1)
btn1 = types.InlineKeyboardButton(text="морфологический разбор", callback_data=f"morphological | {message.text}")
kb.add(btn1)
bot.send_message(message.chat.id, "какой разбор сделать?", reply_markup=kb)
@bot.callback_query_handler(func=lambda callback: callback.data)
def check(callback):
if "morphological" in callback.data:
url = "https://wikislovo.ru/morphology/" + callback.data.split(' | ')[1:]
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
find_text = soup.find('div', class_="morphology-analysis").get_text()
bot.send_message(callback.message.chat.id, find_text)
vk.updates.use(async (context, next) => { //прослушка сообщений
if (!context.senderId) // Если отсуствует id отправителя - выйти
return;
if (context.senderId < 0) // Если сообщение не из лс с ботом - выйти
return;
if (context.isGroup) // Если сообщение от группы - выйти
return;
if (context.is('message') && context.isOutbox) // Если сообщение исходящее - выйти
return;
console.log('[' + await getFirstName(context.senderId) + ']: ' + context.text);
await next(); // Продолжить промежуточный код
});
vk.updates.hear(/!помощь/i, async(context) => {
await context.reply(`Команд нету`);
});
vk.updates.hear
первым аргументом засовывай текст кнопки (точь в точь), а ниже то что будет происходить при нажатии bot = telebot.TeleBot("TOKEN", parse_mode="FORMATING")
TeleBot
telebot.TeleBot.__init__
который вызвается при создании нового экземпляра. import os
import sys
# Returns the directory the current script (or interpreter) is running in
def get_script_directory():
path = os.path.realpath(sys.argv[0])
if os.path.isdir(path):
return path
else:
return os.path.dirname(path)
btn = f"{get_script_directory()}\\ASD.png"