Skip to content

Commit

Permalink
PostBot: Initial commit [skip ci]
Browse files Browse the repository at this point in the history
Change-Id: Ib94756468e601a266da7fcac2882dde606a5de27
Signed-off-by: PrajjuS <[email protected]>
  • Loading branch information
PrajjuS committed Sep 15, 2024
1 parent 90db174 commit 71d31f3
Show file tree
Hide file tree
Showing 4 changed files with 264 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .github/scripts/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Auto Rom Poster Bot

A simple Post Bot written in [Python]('https://www.python.org') using [pyTelegramBotAPI]('https://pypi.org/project/pyTelegramBotAPI') to post rom updates to telegram channel whenever there is an OTA update.

## Instructions

### 1. Adding secrets

Go to your repo `settings > secrets > new repository secret`, and add these secrets.

- `BOT_TOKEN`: Telegram bot token
- `CHAT_ID`: Telegram group/channel chat ID where the rom needs to be posted
- `GH_TOKEN`: Github access token to push changes to repo

**Note:** Bot should be added in the group/channel where the rom needs to be posted

### 2. Running the bot

After adding secrets the next thing is to run the bot.

**We use Github Actions to run the bot**

- Actions will automatically run if any changes are committed to the repo and rom will be posted
- You can also run the bot by going to `actions > Rom Poster Bot Runner > workflow-dispatch` and tap on run

## Credits

- [Ashwin DS](https://github.com/geek0609)
5 changes: 5 additions & 0 deletions .github/scripts/file_ids.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
506c3cd9dfce0f26816fb0d003ac7a54
5cf84a40f6dea8d1cffe2c356c160c5c
c4dd8800cd30c1077d084b4557236765
3eb0185a7835a5ec3c90ee595a9e1b21
5af5de5bb82bc86c7039209888ba1d1a
187 changes: 187 additions & 0 deletions .github/scripts/post.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
#!/usr/bin/env python
#
# Python code which automatically posts Message in a Telegram Group if any new update is found.
# Intended to be run on every push
# USAGE : python3 post.py
# See README for more.
#
# Copyright (C) 2024 PrajjuS <[email protected]>
#
# Credits: Ashwin DS <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import telebot
import os
import json
import datetime
from time import sleep

# Get configs from workflow secrets
def getConfig(config_name: str):
return os.getenv(config_name)
try:
BOT_TOKEN = getConfig("BOT_TOKEN")
CHAT_ID = getConfig("CHAT_ID")
except KeyError:
print("Fill all the configs plox..\nExiting...")
exit(0)

BANNER_PATH = "./assets/banner.jpg"

# Init bot
bot = telebot.TeleBot(BOT_TOKEN, parse_mode="HTML")

# File directories
jsonDir = {
"Gapps": "builds/Gapps",
"Vanilla": "builds/Vanilla"
}
idDir = ".github/scripts"

# Store IDs in a file to compare
def update(IDs):
with open(f"{idDir}/file_ids.txt", "w+") as log:
for ids in IDs:
log.write(f"{str(ids)}\n")

# Return IDs of all latest files from json files
def get_new_id():
files = []
file_id = []
for type, dirName in jsonDir.items():
for all in os.listdir(dirName):
if all.endswith('.json'):
files.append({"type": type, "dir": dirName, "file": all})
for all_files in files:
with open(f"{all_files['dir']}/{all_files['file']}", "r") as file:
data = json.loads(file.read())['response'][0]
file_id.append(data['md5'])
return file_id

# Return previous IDs
def get_old_id():
old_id = []
with open(f"{idDir}/file_ids.txt", "r") as log:
for ids in log.readlines():
old_id.append(ids.replace("\n", ""))
return old_id

# Remove elements in 2nd list from 1st, helps to find out which device got an update
def get_diff(new_id, old_id):
first_set = set(new_id)
sec_set = set(old_id)
return list(first_set - sec_set)

# Grab needed info using ID of the file
def get_info(ID):
files = []
for type, dirName in jsonDir.items():
for all in os.listdir(dirName):
if all.endswith('.json'):
files.append({"type": type, "dir": dirName, "file": all})
for all_files in files:
with open(f"{all_files['dir']}/{all_files['file']}", "r") as file:
data = json.loads(file.read())['response'][0]
if data['md5'] == ID:
device = all_files['file']
build_type = all_files['type']
break
with open(f"{jsonDir[build_type]}/{device}") as device_file:
info = json.loads(device_file.read())['response'][0]
EUCLID_VERSION = info['version']
OEM = info['oem']
DEVICE_NAME = info['device']
DEVICE_CODENAME = device.split('.')[0]
MAINTAINER = info['maintainer']
DATE_TIME = datetime.datetime.fromtimestamp(int(info['timestamp']))
FILENAME = info['filename']
DOWNLOAD_URL = info['download']
BUILD_TYPE = info['buildtype']
SIZE = round(int(info['size'])/1000000000, 2)
MD5 = info['md5']
SHA256 = info['sha256']
XDA = info['forum']
TELEGRAM = info['telegram']
msg = ""
msg += f"Euclid-OS {EUCLID_VERSION}\n"
msg += f"Device Name: {OEM} {DEVICE_NAME} ({DEVICE_CODENAME})\n"
msg += f"Maintainer: {MAINTAINER}\n"
msg += f"Date Time: {DATE_TIME}\n"
# msg += f"Download URL: {DOWNLOAD_URL}\n"
msg += f"Build Type: {BUILD_TYPE}\n"
msg += f"Size: {SIZE}G\n"
msg += f"MD5: {MD5}\n"
msg += f"SHA256: {SHA256}\n"
msg += f"XDA: {XDA}\n"
msg += f"Telegram: {TELEGRAM}\n\n"
print(msg)
return {
"version": EUCLID_VERSION,
"oem": OEM,
"device_name": DEVICE_NAME,
"codename": DEVICE_CODENAME,
"maintainer": MAINTAINER,
"datetime": DATE_TIME,
"filename": FILENAME,
"download": DOWNLOAD_URL,
"buildtype": BUILD_TYPE,
"size": SIZE,
"md5": MD5,
"sha256": SHA256,
"xda": XDA,
"telegram": TELEGRAM
}

# Prepare function for posting message in channel
def send_post(chat_id, image, caption):
return bot.send_photo(chat_id=chat_id, photo=image, caption=caption)

# Prepare message format for channel
def message_content(information):
msg = ""
msg += f"<b>EuclidOS {information['version']} - OFFICIAL | Android 14</b>\n"
msg += f"<b>📲 :</b> <b>{information['oem']} {information['device_name']}</b> <b>(</b><code>{information['codename']}</code><b>)</b>\n"
msg += f"<b>👤 :</b> <a href='https://t.me/{information['maintainer']}'>{information['maintainer']}</a>\n"
msg += f"<b>🗓 :</b> <code>{information['datetime']} UTC</code>\n\n"
msg += f"<b>▪️ Build Variant:</b> <code>{information['buildtype']}</code>\n"
msg += f"<b>▪️ Changelog:</b> <a href='https://raw.githubusercontent.com/euclid-Devices/vendor_euclidOTA/14/changelogs.md'>Source</a> <b>|</b> <a href='https://raw.githubusercontent.com/euclid-Devices/vendor_euclidOTA/14/changelogs/changelog_{information['''codename''']}.txt'>Device</a>\n"
msg += f"<b>▪️ Download:</b> <a href='{information['download']}'>Here</a>\n\n"
msg += f"<b>▪️ Rom Support:</b> <a href='https://t.me/euclidoschat'>Here</a>\n"
msg += f"<b>▪️ Device Support:</b> <a href='{information['telegram']}'>Here</a>\n"
msg += f"\n#euclidOS #{information['codename']} #Android14 #Official"
return msg

# Send updates to channel and commit changes in repo
def tg_message():
commit_message = "Update new IDs and push OTA"
commit_description = "Data for following device(s) were changed:\n"
if len(get_diff(get_new_id(), get_old_id())) == 0:
print("All are Updated\nNothing to do\nExiting...")
sleep(2)
exit(1)
else:
print(f"IDs Changed:\n{get_diff(get_new_id(), get_old_id())}\n\n")
for devices in get_diff(get_new_id(), get_old_id()):
info = get_info(devices)
with open(BANNER_PATH, "rb") as image:
send_post(CHAT_ID, image, message_content(info))
commit_description += f"- {info['device_name']} ({info['codename']})\n"
sleep(5)
update(get_new_id())
open("commit_mesg.txt", "w+").write(f"EuclidOTA: {commit_message} [BOT]\n\n{commit_description}")

# Final stuffs
tg_message()
print("Successful")
sleep(2)
44 changes: 44 additions & 0 deletions .github/workflows/post-bot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Rom Poster Bot

on:
push:
paths:
- "builds/gapps/*.json"
- "builds/vanilla/*.json"
workflow_dispatch:

env:
GitHubMail: "[email protected]"
GitHubName: "EuclidOS-Bot"
GitHubToken: ${{ secrets.GH_TOKEN }}
BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
CHAT_ID: ${{ secrets.CHAT_ID }}

jobs:
post:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Install Dependencies
run: sudo pip install pyTelegramBotAPI

- name: Set Git Configs & Secrets
run: |
git config --global user.email ${GitHubMail}
git config --global user.name ${GitHubName}
git config --global color.ui true
git config --global credential.helper store
echo "https://${GitHubName}:${GitHubToken}@github.com" > ~/.git-credentials
- name: Run RomPosterBot
run: sudo -E python3 .github/scripts/post.py

- name: Commit and Push Changes
run: |
git fetch && git pull
COMMIT_MESSAGE=$(cat commit_mesg.txt)
rm commit_mesg.txt
git add . && git commit -sm "$COMMIT_MESSAGE"
git push origin

0 comments on commit 71d31f3

Please sign in to comment.