O'ZBЕKISTON RESPUBLIKASI AXBOROT TEXNOLOGIYALARI VA KOMMUNIKATSIYALARINI RIVOJLANTIRISH VAZIRLIGI
TOSHKЕNT AXBOROT TЕXNOLOGIYALARI UNIVЕRSITЕTI
“ Mobil ilovalarni ishlab chiqish” fanidan
Mustaqil ish
Mavzu: Telegram API dan foydalanib bot orqali telegram guruhiga yoki kanaliga post qilish , habarlarni tahrirlash,… funksiyalariga ega bo’lgan dastur yaratish
Bajardi: KIF 214-18-guruh talabasi
Jurayev Abdulhayit
Tekshirdi: Talipova O.
Toshkent-2021
Kodni yozish
Python telegram bot api moduli robotning yaratilishi va ishlashi uchun javobgardir. Buning uchun pip o’rnatish pyTelegramBotAPI buyrug’ini yuboring.
Kodni istalgan joyga yozing. Bu Word fayli yoki bloknot bo’lishi mumkin. Ammo buni aqlli muhitda bajarish ancha samaralidir. Mumkin bo’lgan xatolar bu erda avtomatik ravishda ta’kidlanadi.
Kodni yaratish telebotni ulash bilan boshlanadi. Bu erda sizga avval saqlangan token kerak bo’ladi. Birinchi qator quyidagicha ko’rinadi: xabar: TOKEN = bot yuborgan kalit.Ikkinchi satr biz bot deb nomlagan ob’ektni yaratadi. Autentifikatsiya kodi argumentlarda yozilgan.Endi yordamchiga nima qilish kerakligi haqida o’ylash kerak. PyTelegramBotAPI katalogida dekorativlar mavjud, ulardan foydalanishda robot standart savollarga javob berishni o’rganadi.Siz uni python buyrug’ini to’liq_path_to_file / test.py-da ishlatib sinab ko’rishingiz mumkin. robot javob berishi kerak.
Botni sozlang va ishga tushiring
Botni ishga tushirish.
Yordamchi ishlashi uchun sizga quyidagilar kerak:
Xabarchiga kiring.
Robot qayd hisobini oching.
Yangi dialog oynasida yuqori qismida uchta nuqta bo’lgan rasmni bosing.
Sozlamalarga o’ting.
Robotni ishga tushirish uchun sizga kerak:
Qo’llaringiz bilan klaviaturadagi qidirish qatoriga yordamchining ismini kiriting va u bilan suhbatni boshlang.
Uni “Yangi a’zo qo’shish” tugmachasi yordamida kanalga ulang.
Ro’yxatdagi o’zingiz xohlagan variantni tanlang va “taklif qilish” ni bosing.
Buyruq ishlovchilari
Buning uchun maxsus dastur Handler ishlatiladi. U media-fayllar va matnli materiallar bilan ishlaydi. Ammo bizning holatlarimizda yordamchi dastur buyruqlarni botga yuborish uchun kerak.
Siz shuningdek ishlov beruvchini o’zingiz yozishingiz mumkin. Bunday holda, birinchi qatorda “ishlov beruvchida” haydash kerak. Ushbu parametr har doim ishlaydi, “help” yoki “start” kiritishlardan tashqari.
Tugma ishlovchilari
Telegram api python ham klaviatura manbasiga asoslangan bo’ladi. Klaviatura tugmachasini ishga tayyorlashda, kerakli parametr bu tugmachani bosgandan so’ng foydalanuvchi oldinga yuborishi mumkin bo’lgan matndir.
Kod yozishda turli xil usullar qo’llaniladi:
Qo’shish – istalgan sonli tugmalar. Shu bilan birga, ular bir qatorda turishadi. Agar dastlab o’rnatilgan kenglik allaqachon erishilgan bo’lsa, ular o’tkaziladi.
Qator – tugmalar soni ham cheklanmagan, ammo ularning barchasi bir xil chiziqda joylashgan.
Qo’shish – birinchi usulni eslatadi, ammo oxirgi qatorga piktogrammalar qo’shiladi.
O’rnatilgan rejim
Bu botlardan foydalanish uchun bitta variant. Buning yordamida ular yanada ko’proq imkoniyatlarga ega bo’lishdi. Bunday robotlar har qanday vazifani bajarishga qodir. Misollardan misol: saytdan suhbatga matn yuborish, gif yoki rasmni joylashtirish.
Funktsiyani amalda ko’rish uchun bot uchun uning nomi va kalit so’zidan (@gif, @bold, @pic) foydalanib buyruq berish kerak. Bunday holda, robot bir nechta javoblarni taklif qiladi. Foydalanuvchi ulardan birini tanlaydi va suhbatga yuboradi. O’rnatilgan rejim tarixga kira olmaydi, faqat foydalanuvchi unga yozganlariga javob beradi.
import threading
import config
from telebot import types
import sqlalchemy as db
from sqlalchemy import create_engine, Column, String, Integer, func, Date,update
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import telebot
from sqlalchemy import or_
import schedule
import time
import pytz
from datetime import datetime
import json
from time import strptime, struct_time, localtime
bot = telebot.TeleBot(config.token)
base = declarative_base()
class User(base):
__tablename__ = "User"
id = Column('id', Integer, primary_key=True)
user_id = Column('user_id', Integer)
user_number = Column('user_number', Integer)
first_name = Column('first_name',String)
last_name = Column('last_name',String)
class Rejim(base):
__tablename__ = "Rejim"
id = Column('id', Integer, primary_key=True)
user_id = Column('user_id', Integer)
group_id = Column('group_id', Integer)
group_name = Column('group_name', String)
day = Column('day', String)
text = Column('text', String)
time = Column('time',String)
finish = Column('finish',Integer)
class Second_db(base):
__tablename__ = "Second_db"
id = Column('id', Integer, primary_key=True)
user_id = Column('user_id', Integer)
group_id = Column('group_id', Integer)
day = Column('day', String)
days_id = Column('days_id', Integer)
text = Column('text', String)
time = Column('time',String)
finish = Column('finish', Integer)
engine = create_engine('sqlite:///mbaza.db', echo=True, connect_args={'check_same_thread': False})
base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()
metadata = db.MetaData()
user = db.Table('User', metadata, autoload=True, autoload_with=engine)
rejim = db.Table('Rejim', metadata, autoload=True, autoload_with=engine)
second_db = db.Table('Second_db', metadata, autoload=True, autoload_with=engine)
conn = engine.connect()
@bot.message_handler(commands=['groot'])
def posts_from(message):
try:
users_list = bot.get_chat_administrators(message.chat.id)
for i in users_list:
chatid=i.user.id
#chatid = kanal(guruh) dagi adminlarni id si
if (message.from_user.id == chatid):
try:
sess = Session()
tartib = Rejim()
tartib.user_id = message.from_user.id
tartib.group_id = message.chat.id
tartib.group_name = message.chat.title
tartib.finish = 0
sess.add(tartib)
sess.commit()
sess.close()
keyboard_l = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton("🗓 Har hafta", callback_data="hafta_kun")
btn2 = types.InlineKeyboardButton("📅 Har oyda", callback_data="only_one_date")
btn3 = types.InlineKeyboardButton("🔂 Bir martalik", callback_data="only_one")
back = types.InlineKeyboardButton("🔙Ortga", callback_data="one_back")
keyboard_l.add(btn1)
keyboard_l.add(btn2)
keyboard_l.add(btn3)
keyboard_l.add(back)
msg = bot.send_message(message.from_user.id, "🎯 Xabarnoma turini tanlang",
reply_markup=keyboard_l)
bot.delete_message(message.chat.id, message.message_id)
except Exception as e:
bot.send_message(config.admin_id, e)
except Exception as e:
bot.send_message(config.admin_id, e)
@bot.message_handler(func=lambda message: message.forward_from_chat)
def posts_from_channels(message):
users_list = bot.get_chat_administrators(message.forward_from_chat.id)
for i in users_list:
chatid=i.user.id
# chatid = kanal(guruh) dagi adminlarni id s
if (message.chat.id == chatid):
tekshir = 1
try:
sess = Session()
tartib = Rejim()
tartib.user_id = message.chat.id
tartib.group_id = message.forward_from_chat.id
tartib.group_name = message.forward_from_chat.title
tartib.finish = 0
sess.add(tartib)
sess.commit()
sess.close()
keyboard_l = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton("🗓 Har hafta", callback_data="hafta_kun")
btn2 = types.InlineKeyboardButton("📅 Har oyda", callback_data="only_one_date")
btn3 = types.InlineKeyboardButton("🔂 Bir martalik", callback_data="only_one")
back = types.InlineKeyboardButton("🔙Ortga", callback_data="one_back")
keyboard_l.add(btn1)
keyboard_l.add(btn2)
keyboard_l.add(btn3)
keyboard_l.add(back)
msg = bot.send_message(message.chat.id, "🎯 Xabarnoma turini tanlang",
reply_markup=keyboard_l)
except Exception as e:
bot.send_message(config.admin_id, e)
if (tekshir == 0):
bot.send_message(message.chat.id,
"☹️ Siz kanal(guruh) da admin emassiz. To'liq malumot olish uchun \n /help")
def data_time_step(message):
chat_id = message.chat.id
m_text = message.text
try:
if m_text == "🔙Ortga":
keyboard_l = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton("Dushanba", callback_data="Monday")
btn2 = types.InlineKeyboardButton("Seshanba", callback_data="Tuesday")
btn3 = types.InlineKeyboardButton("Chorshanba", callback_data="Wednesday")
btn4 = types.InlineKeyboardButton("Payshanba", callback_data="Thursday")
btn5 = types.InlineKeyboardButton("Juma", callback_data="Friday")
btn6 = types.InlineKeyboardButton("Shanba", callback_data="Saturday")
btn7 = types.InlineKeyboardButton("Yakshanba", callback_data="Sunday")
btn8 = types.InlineKeyboardButton("🔜Keyingi bosqich", callback_data="next")
back = types.InlineKeyboardButton("🔙Ortga", callback_data="back")
keyboard_l.add(btn1, btn2)
keyboard_l.add(btn3, btn4)
keyboard_l.add(btn5, btn6, btn7)
keyboard_l.add(back, btn8)
msg = bot.send_message(chat_id,
"🗓 Xabarnoma jo\'natilishi kerak bo\'lgan hafta kuni(lari)ni belgilang.",
parse_mode='html', reply_markup=keyboard_l)
bot.delete_message(message.chat.id,message.message_id)
elif m_text[2] == ":" and int(m_text[0]) <= 2 and int(m_text[1]) <= 9 and int(m_text[3]) <= 5 and int(
m_text[4]) <= 9 and not (int(m_text[0]) == 2 and int(m_text[1]) >= 4):
session = Session()
up_id = session.query(Rejim).filter(Rejim.user_id == chat_id).filter(Rejim.finish == 0).order_by(Rejim.id.desc()).first().id
session.query(Rejim).filter(Rejim.id == up_id).update({Rejim.time: m_text}, synchronize_session=False)
session.commit()
session.close()
keyboard_l = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton("✅ Ha, matnni yuborish", callback_data="yes_text")
btn2 = types.InlineKeyboardButton("🙅♂️ Yo\'q, qaytadan vaqtni yuborish", callback_data="yes_time")
keyboard_l.add(btn1)
keyboard_l.add(btn2)
bot.send_message(chat_id, "Siz xabarnomani
Do'stlaringiz bilan baham: |