Skip to content

Commit 25e9776

Browse files
committed
Added some features ✨
1 parent 5b710b5 commit 25e9776

File tree

3 files changed

+115
-47
lines changed

3 files changed

+115
-47
lines changed

Diff for: ReadMe.md

+44-18
Original file line numberDiff line numberDiff line change
@@ -6,41 +6,67 @@
66
[![Contributors](https://img.shields.io/github/contributors/jainamoswal/BotStatus?style=for-the-badge&color=green)](https://github.com/jainamoswal/BotStatus)
77

88

9+
910
## BotStatus ~
1011

11-
A simple & short repository to show your bot's status in your GitHub README.md file as well as in you channel.
12+
A simple, short, mostly customisable GitHub Action to show your bot's status in your GitHub MarkDown file as well as in your Telegram.
1213

1314
---
1415
### How to use this ?
15-
1616
- **Star** this repo. ⭐
1717
- Go to the repository where you want to display the status of the bots. 🤖
1818
- Go to environment variables ([Settings ⇢ Secrets ⇢ New Repository Secret.](https://docs.github.com/en/actions/reference/encrypted-secrets)) 🚶
1919
- Fill all Environment variables there. 🤭
2020
- Copy [this](./example.yml) snippet in `./github/workflows/main.yml` in your repository. 📁
21-
- The workflow will automatically run at interval of 3 hours. 🏃
22-
23-
_⚠️ You'll need a bots.json file and list all bots in the JSON format.
24-
It can be raw link from `gist.github.com` or directly by the file itself like `https://github.com/<blabla>/raw/<branchname>/<filename>`. But it should point to the raw source._
21+
- The workflow will automatically run at interval of 3 hours. 🏃
2522

23+
_⚠️ You'll need a valid JSON with all your bots with some additional information. Example is given in example.json, But the link shuld point to raw data like [here](https://gist.githubusercontent.com/jainamoswal/cc331a3d2a4169ab76885c5a1e076d68/raw/579dc4eabce06bc8d4e4e2192449bf1bf53a8193/bots.json). You can use [npoint.io](https://npoint.io), [gist.github.com](https://gist.github.com), [pastebin.com](https://pastebin.com), [JSONKeeper.com](https://jsonkeeper.com) etc..._
24+
25+
> 3rd and 4th steps are not mandatory, It's just to keep your secrets completely secret and not let anyone peep into them. You can also define them directly in `.yml` file.
26+
27+
---
2628

2729
<details>
2830
<summary><b>🤫&nbsp;Environment variables</b></summary>
2931
<br/>
3032

31-
| 🔒 Secret 🔒 | ✍️ Description ✍️ |
32-
| :-: | :-: |
33-
| `API_HASH` | Get it from [my.telegram.org](https://my.telegram.org) |
34-
| `APP_ID` | Get it from [my.telegram.org](https://my.telegram.org) |
35-
| `CHANNEL_ID` | Channel ID eg. -10010254xxxxx |
36-
| `MESSAGE_ID` | Message ID of the message to edit. |
37-
| `SESSION` | [![Run on Repl.it](https://replit.com/badge/github/jainamoswal/SessionString)](https://replit.com/@jainamoswal/SessionString) |
38-
| `BOTS` | Raw link of JSON file of bots. [example](./example.json) |
39-
40-
<b>Optional variables ~ </b>
41-
- `FILE_NAME` : Name of the MarkDown file, eg. `README.md`. This is case sensitive. Defaults to `README.md`.
33+
<b>⌲ These are mandatory variables and should be kept secret. (use [Environment variables](https://docs.github.com/en/actions/reference/encrypted-secrets))</b>
34+
35+
| 🔒 Secret 🔒 | 🏷 Description 🏷 | ⚙️ Default ⚙️ | 📇 Example 📇 |
36+
| :-: | :-: | :-: | :-: |
37+
| `API_HASH` | Get it from [my.telegram.org](https://my.telegram.org) | `None` | `782xxxx` |
38+
| `APP_ID` | Get it from [my.telegram.org](https://my.telegram.org) | `None` | `a1bbfb767fd59812bxxxxxxxxxxxxxxx` |
39+
| `IDS` | IDs of the Messgage followed with `chat id` | `None` | `-100153418xxxx:3 -100225478xxxx:16` |
40+
| `SESSION` | [![Run on Repl.it](https://replit.com/badge/github/jainamoswal/SessionString)](https://replit.com/@jainamoswal/SessionString) | `None` | `xxxxxxxxxxxxxxxx.....` |
41+
| `BOTS` | Raw link of JSON file of bots. | [🔗 Link 🔗](https://gist.githubusercontent.com/jainamoswal/cc331a3d2a4169ab76885c5a1e076d68/raw/579dc4eabce06bc8d4e4e2192449bf1bf53a8193/bots.json) | [JSON format](/example.json)[Raw link](https://gist.githubusercontent.com/jainamoswal/cc331a3d2a4169ab76885c5a1e076d68/raw/579dc4eabce06bc8d4e4e2192449bf1bf53a8193/bots.json) |
42+
43+
44+
**Format of chat IDs » `chat id`:`message id`
45+
Eg, `-100123456xxx:1x` where `100123456xxx` is `chat id` and `1x` is `message id`.**
46+
47+
<details><summary><b>Optional variables</b></summary>
48+
<br>
49+
50+
<b>⌲ These are optional values and can be omitted. Default values will be used. (can use directly in `.yml` instead of messing Environment variables.)</b>
51+
| 🧾 Values 🧾 | 🏷 Description 🏷 | ⚙️ Default ⚙️ | 📇 Example 📇 |
52+
| :-: | :-: | :-: | :-: |
53+
| `FILE_NAME` | Name of the file to edit. | `README.md` | `STATUS.md` |
54+
| `EDIT_IN_REPO` | `True` for editing status in repository, `False` for else. | `True` | `True` |
55+
| `EDIT_IN_TELEGRAM` | True for editing status in repository. | `True` | `True` |
56+
| `START_MESSAGE` | Message to be shown in starting of the Text in Telegram. | _Read [main.py](./main.py)_ | _Read [main.py](./main.py)_ |
57+
| `END_MESSAGE` | Message to be shown in starting of the Text in Telegram. | _Read [main.py](./main.py)_ | _Read [main.py](./main.py)_ |
58+
| `COMMIT_MESSAGE` | Message while commit. | `✨ auto-updated bot status. ✨` | `Updated bot status [Bot]` |
59+
| `BULLET` | The bullet use to separate bots in Telegram. | `` | `` |
60+
| `TIME_ZONE` | The Time zone of your locale. | `Asia/Kolkata` | `Europe/London` |
61+
| `TIME_FORMAT` | Format of your time to be shown everwhere. | `%H:%M %d/%m` | `%Y-%m-%d %H:%M:%S` |
62+
| `UP_GITHUB` | Emoji or Text when the status is up. (on GitHub MarkDown file) | `✔️` | `` |
63+
| `DOWN_GITHUB` | Emoji or Text when the status is down. (on GitHub MarkDown file) | `` | `` |
64+
| `UP_TELEGRAM` | Emoji or Text when the status is up. (in Telegram chat) | `🚀` | `☑️` |
65+
| `DOWN_TELEGRAM` | Emoji or Text when the status is down. (in Telegram chat) | `` | `💤` |
66+
4267
</details>
4368

69+
</details>
4470

4571
<details>
4672
<summary><b>:v: &nbsp;Support me</b></summary>
@@ -66,7 +92,7 @@ It can be raw link from `gist.github.com` or directly by the file itself like `h
6692
<summary><b>💻&nbsp;Credits</b></summary>
6793
<br/>
6894

69-
- [xditya](https://github.com/xditya) for inspiration from [his repo.](https://github.com/xditya/BotStatus)
95+
- [Aditya](https://github.com/xditya) for inspiration from [his repo.](https://github.com/xditya/BotStatus)
7096
- [Lonami](https://github.com/LonamiWebs) for telethon.
7197
- [Google](https://google.com) and [Telethon docs](https://docs.telethon.dev/en/latest) 😅
7298
</details>

Diff for: example.yml

+1-2
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,4 @@ jobs:
1515
SESSION: ${{ secrets.SESSION }} # telethon session string
1616
APP_ID: ${{ secrets.APP_ID }} # APP ID from my.telegram.org
1717
API_HASH: ${{ secrets.API_HASH }} # API ID from my.telegram.org
18-
CHANNEL_ID: ${{ secrets.CHANNEL_ID }} # channel ID of the channel you want to edit the message in.
19-
MESSAGE_ID: ${{ secrets.MESSAGE_ID }} # message id of the message to edit
18+
IDS: ${{ secrets.IDS }} # Message IDs to edit.

Diff for: main.py

+70-27
Original file line numberDiff line numberDiff line change
@@ -3,39 +3,72 @@
33
# Jainam Oswal. <jainam.me>
44

55
# import modules
6-
import os, logging, asyncio, re, github, requests, platform
6+
import os
7+
import re
8+
import github
9+
import logging
10+
import telethon
11+
import requests
12+
import platform
713
from pytz import timezone
814
from datetime import datetime
9-
import telethon
15+
from telethon.errors import MessageIdInvalidError, MessageAuthorRequiredError
1016

1117
print(':::::::::::::::::::::: ⏲️ Action started successfully ⏲️ ::::::::::::::::::::::')
1218
print()
1319
logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.CRITICAL)
1420

15-
# define configs
16-
bots = requests.get(os.getenv('BOTS')).json() # the raw link of the gist file having config data in JSON format
17-
api_id = os.getenv('APP_ID') # API ID from my.telegram.org
18-
api_hash = os.getenv('API_HASH') # APP hash from my.telegram.org
19-
session = os.getenv('SESSION') # session string via telethon
20-
client = telethon.TelegramClient(telethon.sessions.StringSession(session), api_id, api_hash) # none of your bussiness
21-
file_name = 'README.md' if os.getenv('FILE_NAME') is None else os.getenv('FILE_NAME') # filename is case sensitive
21+
# define configs & default configs and blabla...
22+
# Required :-
23+
bots = requests.get(os.getenv('BOTS', 'https://bit.ly/3zzCVJE')).json() # the raw link of the gist file having config data in JSON format. Use mine incase of None provided. 😂
24+
api_id = os.getenv('APP_ID', None) # API ID from my.telegram.org
25+
api_hash = os.getenv('API_HASH', None) # APP hash from my.telegram.org
26+
session = os.getenv('SESSION', None) # session string via telethon.
27+
client = telethon.TelegramClient(telethon.sessions.StringSession(session), api_id, api_hash) # none of your business.
28+
all_mixed_ids = os.getenv('IDS', None) # All Chat IDs along with message IDs (Telegram) to edit in format chat_id:message_id. In case of many, separate them with spaces. Eg, -100123456xxx:8x 123456xx:2xx
29+
30+
# Optional :-
31+
file_name = os.getenv('FILE_NAME', 'README.md') # filename is case sensitive.
32+
edit_in_repo = os.getenv('EDIT_IN_REPO', True) # If you want to edit status in GitHub Repo, set it to True else False.
33+
edit_in_telegram = os.getenv('EDIT_IN_TELEGRAM', True) # If you want to edit status in Telegram, set it to True else False
34+
start_text = "Live status of my bots goes following ~" # default for start_message.
35+
start_message = os.getenv('START_MESSAGE', start_text) # text before the status to show.
36+
end_text = "**Bots status are auto-updated every 3 hours at random frequency.**" # default for end_message.
37+
end_message = os.getenv('END_MESSAGE', end_text) # text after the status to show.
38+
commit_message = os.getenv('COMMIT_MESSAGE', '✨ auto-updated bot status. ✨') # commit message at status update. Btw, stars looks cool.
39+
bullet = os.getenv('BULLET', '◪') # if you want to get custom bullets in Telegram.
40+
time_zone = os.getenv('TIME_ZONE', 'Asia/Kolkata') # ISD. You can choose different as per your location.
41+
time_format = os.getenv('TIME_FORMAT', '%H:%M %d/%m') # Time format, defaults to Hrs:minutes Day/Month. Eg, 9:41 12/9
42+
current_time = datetime.now(timezone(time_zone)).strftime(time_format) # Time when the script runs.
43+
up_github = os.getenv('UP_GITHUB', '✔️') # Custom Icon when Bot is up to show in GitHub MarkDown file.
44+
down_github = os.getenv('DOWN_GITHUB', '❌') # Custom Icon when Bot is down to show in GitHub MarkDown file.
45+
up_telegram = os.getenv('UP_TELEGRAM', '🚀') # Custom Icon when Bot is up to show in Telegram.
46+
down_telegram = os.getenv('DOWN_TELEGRAM', '❌') # Custom Icon when Bot is down to show in Telegram.
2247

2348
# print some information
2449
def display():
25-
print()
26-
print(f"◻️ Telethon version : {telethon.__version__}") # telethon version
27-
print(f"◻️ Platform : {platform.system()}") # system
28-
print(f"◻️ Platform release : {platform.release()}") # system version
29-
print(f"◻️ OS version : {platform.version().split()[0]}") # OS version
30-
print()
50+
print()
51+
print(f"◻️ Telethon version : {telethon.__version__}") # telethon version
52+
print(f"◻️ Platform : {platform.system()}") # system
53+
print(f"◻️ Platform release : {platform.release()}") # system version
54+
print(f"◻️ OS version : {platform.version().split()[0]}") # OS version
55+
print()
56+
57+
# returns a list of proper formatted ids to edit in a looooooop.
58+
def get_ids(all_mixed_ids):
59+
all_chats_with_ids_mix = all_mixed_ids.split(' ')
60+
all_chats = []
61+
for each in all_chats_with_ids_mix:
62+
all_chats.append(each.split(':'))
63+
return all_chats
3164

32-
# updates in ReadMe file at github
65+
# updates in ReadMe file at GitHub
3366
def updateme(old, json_data, first_match, second_match):
3467
new = '''\n| 🤖 Bot 🤖 | ⭐️ Status ⭐️ |\n| :-: | :-: |\n'''
3568
for i in json_data:
36-
new += f"| [{json_data[i]['name']}](https://t.me/{i}) | {'✔️' if json_data[i]['status'] else '❌'} |\n"
37-
new_string = f"\n{first_match}\n{new}\n`Updated last at ~ {datetime.now(timezone('Asia/Kolkata')).strftime('%H:%M:%S on %Y-%m-%d ')} INR` 🏳️‍🌈\n\n"
38-
new_string += f"**Made with ❤️ via [BotStatus](https://github.com/jainamoswal/botstatus)**. \n{second_match}"
69+
new += f"| [{json_data[i]['name']}](https://t.me/{i}) | {up_github if json_data[i]['status'] else down_github} |\n"
70+
new_string = f"\n{first_match}\n{new}\n`Updated last at ~ {current_time}`\n\n"
71+
new_string += f"**Made with ❤️ via [BotStatus](https://github.com/jainamoswal/botstatus)**. \n{second_match}" # self promotion is must ¯\_(ツ)_/¯
3972
return re.sub(f'\n{first_match}.*?{second_match}', new_string, old, flags=re.DOTALL)
4073

4174
# fetch status of all bots listed in the raw gist file
@@ -60,22 +93,32 @@ async def main():
6093
# edit the message with status at telegram
6194
async def edit_message(data):
6295
async with client:
63-
text = 'Live status of my bots goes following ~\n'
96+
text = f'{start_message}\n' # I love f-strings and to comment every line :)
6497
for i in data:
65-
text += f"🔅 [{data[i]['name']}](https://t.me/{i}) ~ {'🚀' if data[i]['status'] else '❌'}\n"
66-
text += f"\n**Last Checked:** \n__{datetime.now(timezone('Asia/Kolkata')).strftime('%Y-%m-%d %H:%M:%S')} IST__\n\n**Bots status are auto-updated every 3 hours at random frequency.**\n\n[J Projects](https://t.me/J_Projects)"
67-
await client.edit_message(int(os.getenv('CHANNEL_ID')), int(os.getenv('MESSAGE_ID')), text, link_preview=False)
98+
text += f"{bullet} [{data[i]['name']}](https://t.me/{i}) ~ {up_telegram if data[i]['status'] else down_telegram}\n"
99+
text += f"\n**Last Checked:** \n__{current_time}__\n"
100+
text += end_message
101+
chats_to_edit = get_ids(all_mixed_ids)
102+
for chat_id, message_id in chats_to_edit:
103+
try:
104+
await client.edit_message(int(chat_id), int(message_id), text, link_preview=False)
105+
except MessageIdInvalidError:
106+
print(f'Provided message ID ({message_id}) is invalid of chat ({chat_id}), Maybe message Id representing the Message is Deleted or was not sent before.')
107+
except MessageAuthorRequiredError:
108+
print(f'You don\'t have enough rights to edit this message.\n Chat : {chat_id} with Message {message_id}')
68109

69110
# run the script via __main__ style
70111
if __name__ == '__main__':
71112
json_data = client.loop.run_until_complete(main())
72113
display()
73114
for each in json_data:
74115
print(f"🔸 {json_data[each]['name']} [@{each}] is {'🟢' if json_data[each]['status'] else '🔴'}")
75-
client.loop.run_until_complete(edit_message(json_data))
76-
repo = github.Github(os.getenv('GITHUB_TOKEN')).get_repo(os.getenv('GITHUB_REPOSITORY'))
77-
contents = repo.get_contents(file_name)
78-
repo.update_file(file_name, "✨ auto-updated bot status. ✨", updateme(contents.decoded_content.decode(), json_data, '<start>', '<end>'), contents.sha)
116+
if edit_in_telegram:
117+
client.loop.run_until_complete(edit_message(json_data))
118+
if edit_in_repo:
119+
repo = github.Github(os.getenv('GITHUB_TOKEN')).get_repo(os.getenv('GITHUB_REPOSITORY'))
120+
contents = repo.get_contents(file_name)
121+
repo.update_file(file_name, commit_message, updateme(contents.decoded_content.decode(), json_data, '<start>', '<end>'), contents.sha)
79122

80123
print()
81124
print('::::::::::::::::::::: 🎉 Action completed successfully 🎉 :::::::::::::::::::::')

0 commit comments

Comments
 (0)