commit 154ceb7faa3b6b669ac177c3fa8bde803157d425 Author: Kusaeni Date: Sun Sep 29 17:14:20 2024 +0700 pertama komit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e62599e --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__ +.env +*.db +belajar-fetch diff --git a/README.md b/README.md new file mode 100644 index 0000000..adf24ac --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Python Gotosocial Notifikasi + +Ini adalah script untuk mengambil notifikasi di instance kauaku.us (gotosocial) dan menyimpannya ke database sqlite. + +kemudian mengirimkannya dengan telegram bot. diff --git a/main.py b/main.py new file mode 100644 index 0000000..b5cf9eb --- /dev/null +++ b/main.py @@ -0,0 +1,97 @@ +# %% +# ZED Python REPL + +import requests +import os +import logging +import asyncio +import telegram +from json import dumps +from models import Notifikasi, Session +from sqlalchemy import and_, or_, func +from sqlalchemy.exc import IntegrityError +from dotenv import load_dotenv +from datetime import datetime + +# Request ke kauaku +load_dotenv() +gts_api = os.getenv('GTS_API') +gts_token = os.getenv('GTS_TOKEN') + +headers = {"Authorization": f"Bearer {gts_token}"} + +session = Session() + +TELE_BOT = os.getenv('TELE_BOT') +TELE_CHATID = os.getenv('TELE_CHATID') +bot = telegram.Bot(token=f'{TELE_BOT}') + +def getNotif(): + req = requests.get(f'{gts_api}?limit=5', headers=headers) + + if req.status_code == 200: + data = req.json() + try: + for notif in data: + type = notif['type'] + inreply = notif['status']['in_reply_to_id'] + postid = notif['id'] + created = datetime.strptime(notif['created_at'], "%Y-%m-%dT%H:%M:%S.%fZ") + handler = notif['account']['acct'] + username = notif['account']['display_name'] + status = notif['status']['content'] + url = notif['status']['url'] + kirim = 'Belum' + + if type == 'follow': + insert_follow = Notifikasi(post_id=postid, created_at=created, handler=handler, display_name=username, type=type, remark=kirim) + session.add(insert_follow) + else: + insert_mentions = Notifikasi(post_id=postid, created_at=created, handler=handler, display_name=username, type=type, status=status,url=url, remark=kirim) + + session.add(insert_mentions) + session.commit() + + except IntegrityError as err: + session.rollback() + if 'post_id' in str(err.orig): + print("Post Id sudah ada") + else: + print(f"Integritas data bermasalah", str(err)) + finally: + session.close() + + +async def kirim_ke_tele(): + cek_data = session.query(Notifikasi).filter(Notifikasi.remark.like('%elu%')).limit(10).all() + + + for notif in cek_data: + body = { + 'text': 'text', + 'chat_id': {str(TELE_CHATID)}, + 'parse_mode': 'markdown', + 'text': f"{notif.post_id} : {notif.handler}" + } + + if str(notif.type) == 'Follow': + try: + req = requests.post(f"https://api.telegram.org/bot{TELE_BOT}/sendMessage", headers=headers, data="fuck") + except: + print('Ada masalah saat kirim ke Telebot') + else: + try: + await bot.send_message(chat_id=str(TELE_CHATID), text=f""" + {notif.display_name}\n{notif.handler} + + {notif.status} + """ + ) + + except Exception as e: + print(f'Ada masalah saat kirim ke Telebot1', e) + + + +# getNotif() +asyncio.run(kirim_ke_tele()) diff --git a/models.py b/models.py new file mode 100644 index 0000000..fbf81a9 --- /dev/null +++ b/models.py @@ -0,0 +1,37 @@ +# %% +# ZED Python REPL + +from enum import unique +from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date +from sqlalchemy.orm import sessionmaker +from sqlalchemy.ext.declarative import declarative_base + +# Engine +engine = create_engine('sqlite:///gotodon.db') + +# Base +Base = declarative_base() + +# Models +class Notifikasi(Base): + __tablename__ = 'notifikasi' + + id = Column(Integer, primary_key=True) + inreplyto = Column(String) + post_id = Column(String, unique=True) + created_at = Column(Date) + handler = Column(String) + display_name = Column(String) + type = Column(String) + status = Column(String) + url = Column(String) + remark = Column(String) + + def __repr__(self) -> str: + return f"<{self.id} : {self.handler} >" + +# Buat tabel +Base.metadata.create_all(engine) + +# Session +Session = sessionmaker(bind=engine) diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 0000000..820f516 --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "venvPath": ".", + "venv": "belajar-fetch" +} diff --git a/snippets.py b/snippets.py new file mode 100644 index 0000000..04e76ad --- /dev/null +++ b/snippets.py @@ -0,0 +1,47 @@ +# %% +import requests +import json +#import pandas as pd + +api = 'https://jsonplaceholder.typicode.com/users' + +req = requests.get(api) +nama = [] +alamat = [] + +if req.status_code == 200: + data = req.json() + + for d in data: + nama = d['name'] + jalan = d['address']['street'] + suite = d['address']['suite'] + kota = d['address']['city'] + + + print(f"nama: {nama} {jalan} {suite} ,{kota}") + +else: + print(f'Gagal mengambil data') + +# Python akses variable di dalam loop dari luar +if req.status_code == 200: + data = req.json() + + n = [] + k = [] + + for d in data: + nama = d['name'] + kota = d['address']['city'] + + n.append(nama) + # j.append(jalan) + # s.append(suite) + k.append(kota) + + print(f"{n} : {k}") + + +else: + print(f'Gagal mengambil data')