from threading import Thread
from time import sleep
def print_some1(txt):
while True:
print(f'{print_some1.__name__} - {txt}')
sleep(.5)
def print_some2(txt, n):
while n < 10:
n += 1
print(f'{print_some2.__name__} - {txt}')
sleep(.75)
if __name__ == '__main__':
text = 'some text message'
Thread(target=print_some1, args=(text,)).start()
Thread(target=print_some2, args=(text, 1)).start()
import telebot
from telebot import types
token = ""
bot = telebot.TeleBot(token)
contacs = {'sales': '8 (888) 888888, доб. 300',
'support': '8 (888) 888888, доб. 301',
'accounting': '8 (888) 888888, доб. 302',
'address': 'Наш адрес находится по адресу - адрес'}
@bot.message_handler(commands=['start'])
def handle_start(message):
keyboardmain = types.InlineKeyboardMarkup()
help = types.InlineKeyboardButton(text="Помощь", callback_data="help")
contacts = types.InlineKeyboardButton(text="Адрес офиса", callback_data="address")
site = types.InlineKeyboardButton(text="Перейти на сайт", callback_data="site", url='https://qna.habr.com/q/889613')
keyboardmain.add(help, contacts, site)
text = 'Добро пожаловать в Telegram бот компании "Лайт".'
bot.send_message(chat_id=message.chat.id, text=text, reply_markup=keyboardmain)
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
keyboardmain = types.InlineKeyboardMarkup()
help = types.InlineKeyboardButton(text="Помощь", callback_data="help")
contacts = types.InlineKeyboardButton(text="Адрес офиса", callback_data="address")
site = types.InlineKeyboardButton(text="Перейти на сайт", callback_data="site", url='https://qna.habr.com/q/889613')
buttons = [help, contacts, site]
text = contacs.get(call.data, None)
if call.data == 'help':
accounting = types.InlineKeyboardButton(text="Бухгалтерия", callback_data="accounting")
support = types.InlineKeyboardButton(text="Техподдержка", callback_data="support")
sales = types.InlineKeyboardButton(text="Отдел продаж", callback_data="sales")
back = types.InlineKeyboardButton(text="Назад", callback_data="back")
buttons = [accounting, support, sales, back]
text = 'Выберите пункт меню: '
if call.data == 'accounting':
back = types.InlineKeyboardButton(text="Назад", callback_data="back")
buttons.append(back)
if call.data == 'support':
back = types.InlineKeyboardButton(text="Назад", callback_data="back")
buttons.append(back)
if call.data == 'sales':
back = types.InlineKeyboardButton(text="Назад", callback_data="back")
buttons.append(back)
if call.data == 'address':
back = types.InlineKeyboardButton(text="Назад", callback_data="back")
buttons.append(back)
keyboardmain.add(*buttons)
bot.send_message(chat_id=call.message.chat.id, text=text, reply_markup=keyboardmain)
if __name__ == "__main__":
try:
bot.polling(none_stop=True)
except Exception as Error:
print(Error)
import telebot
token= ""
bot = telebot.TeleBot(token)
const = 9
def multiply(num):
return num * const
@bot.message_handler(func=lambda m: True)
def catch_all(message):
if message.text.isdigit():
bot.send_message(message.chat.id, multiply(int(message.text)))
if __name__ == "__main__":
try:
bot.polling(none_stop=True)
except Exception as Error:
print(Error)
a = [
{
"appid": 211050,
"name": "GG"
},
{
"appid": 1900,
"name": "CS"
},
{
"name": "GO"
}
]
for i in a:
print(i.get('appid', None))
from msvcrt import getch
from threading import Thread
def catch_key():
while True:
n = getch()
Thread(target=main, args=(n,)).start()
if ord(n) == 27: # esc
break
def main(key):
print(f'{key} - {ord(key)}')
if __name__ == '__main__':
catch_key()
>>> url1 = 'http://www.sovmusic.ru/m32/officers.mp3'
>>> import requests
>>> r = requests.get(url1)
>>> import os
>>> os.getcwd()
'C:\\Users\\Aleksandr'
>>> with open('officers.mp3' , 'wb') as f:
... f.write(r.content)
...
696969
>>>
>>> os.listdir()
['Documents', 'Downloads', 'Favorites', 'officers.mp3']
>>> long_str = '''Какой-то текст 1
... Какой-то текст 2
... Какой-то текст 3
... Какой-то текст 4
... и тд'''
>>> long_str
'Какой-то текст 1\nКакой-то текст 2\nКакой-то текст 3\nКакой-то текст 4\nи тд'
>>> long_str[long_str.find('\n')+1:]
'Какой-то текст 2\nКакой-то текст 3\nКакой-то текст 4\nи тд'
>>> print(long_str[long_str.find('\n')+1:])
Какой-то текст 2
Какой-то текст 3
Какой-то текст 4
и тд
>>>
create table `rules` (`id` INT PRIMARY KEY, `rule` VARCHAR(50));
insert into `rules` (`id`, `rule`) VALUES (1, 'user');
insert into `rules` (`id`,`rule`) VALUES (2, 'moderator');
insert into `rules` (`id`,`rule`) VALUES (3,'admin');
create table `users` (`telegram_id` INT PRIMARY KEY, `username` VARCHAR(50), `status` INT, FOREIGN KEY (`status`) REFERENCES `rules` (`id`));
insert into `users` (`telegram_id`, `username`, `status`) VALUES (555, 'user555', '1');
insert into `users` (`telegram_id`, `username`, `status`) VALUES (666, 'user666', '2');
insert into `users` (`telegram_id`, `username`, `status`) VALUES (777, 'user777', '3');
insert into `users` (`telegram_id`, `username`, `status`) VALUES (888, 'user888', '3');
select u.username from users u
left join rules r
ON u.status=r.id
where id=3;
def hour_rounder(t):
# Rounds to nearest hour by adding a timedelta hour if minute >= 30
dt = t.replace(second=0, microsecond=0, minute=0, hour=t.hour) + timedelta(hours=t.minute // 30)
ts = int(dt.timestamp())
return str(ts)
print(hour_rounder(datetime.now()))
import xml.etree.ElementTree as ET
xml_file = r'C:\metadata.xml'
tree = ET.parse(xml_file)
root = tree.getroot()
for elem in root.findall('meta'):
meeting_name = elem.find('meetingName').text
sql = r"..."
cursor.execute(sql, [uid])
id = 123
name = 'alekssamos'
sql = "SELECT * FROM TABLE WHERE id = ? and name = ?"
cursor.execute(sql, (id, name))
from tkinter import *
def check_bmi(h, w, a):
bmi = round(w / (h / 100) / (h / 100), 2)
if bmi < 16.5:
result = 'очень плохо'
elif 16.5 <= bmi < 18.5:
result = 'недостаточная масса тела'
elif 18.5 <= bmi < 25:
result = 'нормальный вес'
elif 25 <= bmi < 30:
result = 'избыточная масса тела'
else:
result = 'Ожирение!'
return result
def bmi_index():
if not entry1.get() or not entry2.get() or not entry3.get():
label4.configure(text='заполните все поля')
label4.pack()
else:
height = float(entry1.get())
weight = float(entry2.get())
age = int(entry3.get())
bmi = check_bmi(height, weight, age)
entry1.delete(0, END)
entry2.delete(0, END)
entry3.delete(0, END)
label4.configure(text=bmi)
label4.pack()
if __name__ == '__main__':
root = Tk()
f1 = Frame()
f1.pack(side=LEFT, padx=10)
entry1 = Entry(f1)
label1 = Label(f1, text="рост в см", justify=LEFT)
entry2 = Entry(f1)
label2 = Label(f1, text="вес в кг", justify=LEFT)
entry3 = Entry(f1)
label3 = Label(f1, text="возраст полных лет", justify=LEFT)
label1.pack(fill=X)
entry1.pack(fill=X)
label2.pack(fill=X)
entry2.pack(fill=X)
label3.pack(fill=X)
entry3.pack(fill=X)
f2 = Frame()
f2.pack(side=LEFT, padx=10)
badd = Button(f2, text="подсчитать", background="#555", foreground="#ccc",
padx="20", pady="8", font="16", command=bmi_index)
badd.pack(fill=X)
label4 = Label(f2, text="", justify=LEFT)
label4.pack(fill=X)
root.mainloop()