Skip to content

Instantly share code, notes, and snippets.

@exemplum100
Created July 16, 2023 07:31
Show Gist options
  • Save exemplum100/3cd8a61f15480b4e3f2a312ce299a4bd to your computer and use it in GitHub Desktop.
Save exemplum100/3cd8a61f15480b4e3f2a312ce299a4bd to your computer and use it in GitHub Desktop.
Пример использования Python с Telegram
import config
import telebot
import re
import time
import datetime
from threading import Thread
import schedule
from time import sleep
import requests
import random
import os
import bs4
from urllib.request import Request, urlopen
import sqlite3
import shelve
import threading
lock = threading.Lock()
conn = sqlite3.connect("msgs.db",check_same_thread=False)
cursor = conn.cursor()
import psycopg2
conn1 = psycopg2.connect(dbname='postgres', user='postgres',
password='', host='localhost')
cursor1 = conn1.cursor()
s_city = "Moscow"
city_id = 524901
appid = ""
info1=[]
timers=[0]
m=[1]
mci=[]
mfu=[0]
dmci=[]
dmms=[0]
mms=[0]
mmsbot=[0]
bot = telebot.TeleBot(config.token)
def schedule_checker():
while True:
schedule.run_pending()
sleep(60)
@bot.message_handler(commands=['del'])
def delmsgchat(message):
userid=message.from_user.id
cursor1.execute('SELECT msgid FROM albums where userid = %s',(userid,))
for row in cursor1:
print(str(row[0]))
try:
bot.delete_message(-100000000,row[0])
except:
pass
print('start del')
cursor1.execute('DELETE FROM albums WHERE userid = %s',(userid,))
conn1.commit()
bot.delete_message(-000000,message.message_id)
@bot.message_handler(commands=["temp"])
def start(message):
key=message.chat.id
print(key)
if key ==(-1000000000000):
try:
res = requests.get("http://api.openweathermap.org/data/2.5/weather",
params={'id': city_id, 'units': 'metric', 'lang': 'ru', 'APPID': appid})
data = res.json()
x=str(data['weather'][0]['description'])
x1=str(data['main']['temp'])
bot.send_chat_action(message.chat.id, 'typing')
time.sleep(2)
bot.send_message(message.chat.id,"Облачность: "+ x + ". Температура: "+x1)
print(message.chat.id)
except Exception as e:
print("Exception (weather):", e)
pass
@bot.message_handler(commands=["g"])
def messages(message):
url = 'https://www.elle.ru/astro/'
slovar1=["aries","taurus","gemini","cancer","leo","virgo","libra","scorpio","sagittarius","capricorn","aquarius","pisces"]
slovar2=["овен","телец","близнецы","рак","лев","дева","весы","скорпион","стрелец","козерог","водолей","рыбы"]
slovo2= message.text
slovo2=slovo2[3:]
key=message.chat.id
if slovo2 in slovar2 and key ==(-10000000):
i= slovar2.index(slovo2)
url= url+slovar1[i]+"/day/"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
soup = bs4.BeautifulSoup(webpage, 'html.parser')
#price = soup.find('span', 'arial_26 inlineblock pid-13679-last').get_text()
bal = soup.find('div', 'articleParagraph articleParagraph_dropCap').get_text()
bot.send_chat_action(message.chat.id, 'typing')
time.sleep(2)
bot.reply_to(message, bal)
@bot.message_handler(commands=["start"])
def start(message):
bot.send_chat_action(message.chat.id, 'typing')
time.sleep(2)
bot.send_message(message.chat.id, "Я работаю только в чате! (Необходимо дать доступ к сообщениям)")
######################################################################
#@bot.message_handler(content_types=["new_chat_members"])
def delusr(message):
#bot.get_chat_member(chat_id, user_id)
msg=bot.reply_to(message, 'Ожидайте подтверждение адмнистратора.')
#permissions =(can_send_messages = False,can_send_media_messages = False,can_send_other_messages = False)
bot.restrict_chat_member(message.chat.id, message.from_user.id, can_send_messages = False,can_send_media_messages = False,can_send_other_messages = False)
info1.append(message.from_user.id)
info1.append(message.from_user.first_name)
info1.append(message.from_user.last_name)
info1.append(message.from_user.username)
mms.append(message.message_id)
mci.append(message.chat.id)
fx = open('1textusr.txt', 'a',encoding='utf-8')
for i in info1:
fx.write(str(i)+ ';')
fx.write("\n")
fx.close()
info1.clear()
print(1)
#@bot.message_handler(regexp=r"Слово")
def delusr(message):
if message.text == "Слово" and message.from_user.id == mfu[-1]:
dmms.append(message.message_id)
dmci.append(message.chat.id)
msg=bot.send_message(message.chat.id, 'Добро пожаловать!')
mmsbot.append(msg.message_id)
m.append(1)
@bot.message_handler(commands=["mus"])
def start(message):
x=open('text.txt', 'r')
a = []
for s in x.readlines():
new=s.strip('\n')
a.append(new)
ran=random.randint(1,len(a))
dobav=a[ran]
bot.send_audio(message.chat.id, dobav, timeout=5)
bot.delete_message(-100000000,message.message_id)
#@bot.message_handler(commands=["musq"])
def start(message):
f=[]
if len(os.listdir('musbot/'))> len(f):
bot.send_message(message.chat.id, "Загружаю...")
for file in os.listdir('musbot/'):
if file.split('.')[-1]== 'mp3':
f.append(file)
x= random.randint(1,len(f))
audio = open('musbot/'+f[x], 'rb')
bot.send_audio(message.chat.id, audio, timeout=5)
#bot.send_audio(message.chat.id, "FILEID")
@bot.message_handler(commands=["mus3"])
def start(message):
bot.send_chat_action(message.chat.id, 'typing')
time.sleep(2)
bot.send_message(message.chat.id, "Пример текста")
x=open('text.txt', 'r')
a = []
for s in x.readlines():
new=s.strip('\n')
a.append(new)
for i in range(3):
ran=random.randint(1,len(a))
dobav=a[ran]
bot.send_audio(message.chat.id, dobav, timeout=5)
time.sleep(1)
@bot.message_handler(commands=['parsmus'])
def find_file_ids(message):
for file in os.listdir('musbot/'):
if file.split('.')[-1] == 'mp3':
f = open('musbot/'+file, 'rb')
fx = open('text.txt', 'a')
msg = bot.send_audio(message.chat.id, f, None)
fx.write(msg.audio.file_id+ '\n')
fx.close()
print(1)
@bot.message_handler(commands=['probki'])
def deljoinchat(message):
key=message.chat.id
print(key)
if key ==(-1000000000):
img = requests.get("https://static-maps.yandex.ru/1.x/?ll=37.440311,55.749115&spn=0.1,0.1&l=map,trf")
img_file = open('1pngmap.png', 'wb')
img_file.write(img.content)
img_file.close()
photo = open('1pngmap.png', 'rb')
bot.send_photo(message.chat.id, photo)
@bot.message_handler(commands=['foxyday'])
def foxyday(message):
key=message.chat.id
if key ==(-100000000000):
with lock:
userid=message.from_user.id
sql="SELECT fname FROM foxyday where userid="+str(userid)
cursor.execute(sql)
x=cursor.fetchall()
if x==[]:
#этап регистрации
# cursor.execute("""CREATE TABLE foxyday
# (pmkey integer, userid integer, fname text,lname text ,cntfox integer)
# """)
pmkey=1
fname=message.from_user.first_name
lname=message.from_user.last_name
cntfox=0
albums = [(pmkey, userid,fname,lname,cntfox)]
cursor.executemany("INSERT INTO foxyday VALUES (?,?,?,?,?)", albums)
conn.commit()
bot.reply_to(message, 'Вы зарегистрированы на мероприятие "Слово дня!"')
else:
with shelve.open('timer1') as tkeys:
last=tkeys.get("time", "2022-06-09-21.02.10")
today = datetime.datetime.today()
last=datetime.datetime.strptime(last, '%Y-%m-%d-%H.%M.%S')
delta= today - last
delta=delta.days
print(delta)
if delta>=1:
sql='SELECT userid,fname, lname FROM foxyday WHERE userid IS NOT NULL ORDER BY RANDOM() LIMIT 1'
cursor.execute(sql)
foxuser=cursor.fetchall()
print(foxuser)
bot.send_chat_action(-10000000000, 'typing')
time.sleep(2)
bot.send_message(-10000000000, "Слово дня: "+str(foxuser[0][1]))
today = datetime.datetime.today()
timestr=today.strftime("%Y-%m-%d-%H.%M.%S")
with shelve.open('timer1') as tkeys:
tkeys["time"] = timestr
sql="SELECT cntfox FROM foxyday where userid="+str(foxuser[0][0])
cursor.execute(sql)
cntfox1=cursor.fetchall()
print(cntfox1)
print(userid)
cntfox1=cntfox1[0][0]+1
sql = 'UPDATE foxyday SET cntfox ='+str(cntfox1)+' WHERE userid ='+str(foxuser[0][0])
cursor.execute(sql)
conn.commit()
print(cntfox1)
print('foxydone')
else:
bot.reply_to(message, '"Слово дня" уже проводилась!')
@bot.message_handler(commands=['frate'])
def foxydayrank(message):
with lock:
sql='SELECT fname, cntfox FROM foxyday ORDER BY cntfox DESC LIMIT 3'
cursor.execute(sql)
foxuser=cursor.fetchall()
bot.send_chat_action(-10000000, 'typing')
time.sleep(2)
bot.send_message(-100000000000, "Самые лучшие за всё время: \n"+str(foxuser[0][0])+ ". Рейтинг: "+str(foxuser[0][1])+ '\n'+str(foxuser[1][0])+ ". Рейтинг: "+str(foxuser[1][1])+ '\n'+str(foxuser[2][0])+ ". Рейтинг: "+str(foxuser[2][1]))
@bot.message_handler(content_types=["text"])
def handle_text(message):
#sql = "SELECT max(pkmsg) FROM albums"
#cursor.execute(sql)
#pkmsg=cursor.fetchone()
pkmsg=10001
userid=message.from_user.id
msgid=message.message_id
fname=message.from_user.first_name
lname=message.from_user.last_name
usern=message.from_user.username
msg=message.text
albums = [userid, msgid, fname, lname,usern,msg]
cursor1.execute("INSERT INTO albums (userid, msgid, fname, lname,usern,msg) VALUES (%s,%s,%s,%s,%s,%s)", albums)
conn1.commit()
albums = [(pkmsg, userid, msgid, fname, lname,usern,msg)]
# try:
# cursor.executemany("INSERT INTO albums VALUES (?,?,?,?,?,?,?)", albums)
# conn.commit()
# except:
# pass
try:
cursor.executemany("INSERT INTO albums_arc VALUES (?,?,?,?,?,?,?)", albums)
conn.commit()
except:
pass
@bot.message_handler(content_types=['photo'])
def photo(message):
userid=message.from_user.id
msgid=message.message_id
fname=message.from_user.first_name
lname=message.from_user.last_name
usern=message.from_user.username
msg="Фото"
albums = [userid, msgid, fname, lname,usern,msg]
cursor1.execute("INSERT INTO albums (userid, msgid, fname, lname,usern,msg) VALUES (%s,%s,%s,%s,%s,%s)", albums)
conn1.commit()
if __name__ == '__main__':
#schedule.every(60).seconds.do(deljoinchat)
#schedule.every(60).seconds.do(delusr1)
#schedule.every(60).seconds.do(utro)
schedule.every().day.at('07:00').do(utro)
schedule.every().day.at('15:30').do(obed)
Thread(target=schedule_checker).start()
bot.infinity_polling(timeout=10, long_polling_timeout = 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment