Skip to content
This repository has been archived by the owner on Jan 11, 2024. It is now read-only.

Commit

Permalink
Merge pull request #24 from aahniks/let-admin-config
Browse files Browse the repository at this point in the history
Let admins configure more
  • Loading branch information
aahnik authored Jun 27, 2021
2 parents df3eead + b46b67a commit 9fbc54c
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 27 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
# refer-bot

## Environment Variables

"TG_API_ID"

"TG_API_HASH"

"TG_BOT_TOKEN"

"TG_BOT_ADMINS" # comma seperated usernames of admins

"TG_BOT_CONTACT_ADMIN"

"MONGO_DB_CON_STR", "mongodb://localhost:27017/"

"MONGO_DB_DATABASE", "test"

"WITHDRAWALS_CHANNEL"

"BRODCASTER_CHANNEL"
9 changes: 8 additions & 1 deletion refer_bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,17 @@ async def start_bot():
motor_client = AsyncIOMotorClient(conf.MONGO_DB_CON_STR)
logging.info(f"Created motor client for '{conf.MONGO_DB_CON_STR}'")
engine = AIOEngine(motor_client=motor_client, database=conf.MONGO_DB_DATABASE)
st.engine = engine
logging.info(
f"Created AsyncIO Engine for MongoDB for '{conf.MONGO_DB_DATABASE}' database"
)
st.engine = engine

await asyncio.sleep(5)

st.admin_cfg = await st.engine.find_one(st.AdminConfig, st.AdminConfig.one_id == 1)
if not st.admin_cfg:
st.admin_cfg = await st.engine.save(st.AdminConfig(one_id=1))
logging.info("Loaded admin config")

conf.ADMINS = [await get_id(client, admin) for admin in conf.BOT_ADMINS.split(",")]
logging.info(f"Usernames of bot admins {conf.BOT_ADMINS}")
Expand Down
4 changes: 2 additions & 2 deletions refer_bot/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
CONTACT_ADMIN = os.getenv("TG_BOT_CONTACT_ADMIN")
MONGO_DB_CON_STR = os.getenv("MONGO_DB_CON_STR", "mongodb://localhost:27017/")
MONGO_DB_DATABASE = os.getenv("MONGO_DB_DATABASE", "test")
TG_CHANNELS = os.getenv("TG_CHANNELS")
WITHDRAWALS_CHANNEL = os.getenv("WITHDRAWALS_CHANNEL")
BRODCASTER_CHANNEL = os.getenv("BRODCASTER_CHANNEL")

COMMANDS = {
"start": "start the bot",
Expand All @@ -22,7 +23,6 @@

ADMINS = [] # user id of admins

CHANNELS = TG_CHANNELS.split(",")
BOT_USERNAME = ""


Expand Down
17 changes: 13 additions & 4 deletions refer_bot/handlers/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,22 @@ def get_args(text: str) -> str:
return args


async def check_joined(client: TelegramClient, user: int):
for channel in conf.CHANNELS:
async def check_joined(
client: TelegramClient,
user: int,
channels=None,
raise_err: bool = False,
):
if not channels:
channels = st.admin_cfg.force_channels
for channel in channels:
try:
await client(functions.channels.GetParticipantRequest(channel, user))
except UserNotParticipantError:
return False
except Exception as err:
if raise_err:
raise err
logging.exception(f"Could not check joined for channel {channel}")
continue
return True
Expand Down Expand Up @@ -136,8 +145,8 @@ async def wrapper_func(event: EventLike):

async def show_channels(event: EventLike):
channels = ""
for c in conf.CHANNELS:
channels += f"➟ {c}\n"
for i, c in enumerate(st.admin_cfg.force_channels, start=1):
channels += f"➟ [Channel {i}]({c})\n"
await event.respond(
messages.join_channels_text.format(channels=channels),
buttons=[
Expand Down
72 changes: 56 additions & 16 deletions refer_bot/handlers/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,10 @@

from refer_bot import __version__, messages
from refer_bot import storage as st
from refer_bot.handlers._utils import admin_protect, build_keyboard
from refer_bot.handlers._utils import admin_protect, build_keyboard, check_joined
from refer_bot.types import EventLike

configure_btn = "🛠️ Configure"
edit_user_btn = "✏️ Edit User"
stats_btn = "📊 View Statistics"
contact_dev_btn = "🧑‍💻 Contact Developer"

admin_btns = build_keyboard(
[[configure_btn, edit_user_btn], [stats_btn], [contact_dev_btn]]
)
admin_btns = build_keyboard(messages.admin_kbd_matrix)


@events.register(events.NewMessage(pattern="/admin"))
Expand All @@ -25,13 +18,60 @@ async def admin_cmd_handler(event: EventLike):
)


@events.register(events.NewMessage(pattern=configure_btn))
@events.register(events.NewMessage(pattern=messages.configure_btn))
@admin_protect
async def configure_btn_handler(event: EventLike):
await event.respond("This feature is coming in the next release!")
button_data = {
messages.edit_channels_btn: "force_channels",
messages.edit_min_lim_btn: "min_lim",
messages.edit_coin_val: "coin_val",
}
admin_config_kbd = build_keyboard(messages.admin_config_kbd_matrix)

client: TelegramClient = event.client

admin_cfg = await st.engine.find_one(st.AdminConfig, st.AdminConfig.one_id == 1)
if not admin_cfg:
admin_cfg = await st.engine.save(st.AdminConfig(one_id=1))

async with client.conversation(event.sender_id) as conv:
ask_optn = await conv.send_message(
messages.admin_config.format(cfg=st.admin_cfg), buttons=admin_config_kbd
)
user_optn = await conv.get_response(ask_optn)
ch = button_data.get(user_optn.text)
if not ch:
await conv.send_message("Invalid Choice", buttons=admin_btns)
raise events.StopPropagation
ask_val = await conv.send_message(
f"Enter the value of {ch}", buttons=Button.clear()
)
user_ans = await conv.get_response(ask_val)
val: str = user_ans.raw_text
if ch == "force_channels":
val = val.strip().split("\n")
try:
setattr(admin_cfg, ch, val)
await check_joined(
client,
event.sender_id,
channels=admin_cfg.force_channels,
raise_err=True,
)
except Exception as err:
await conv.send_message("❌ " + str(err))
else:
st.admin_cfg = await st.engine.save(admin_cfg)
await conv.send_message("✅ Success!")
finally:
await conv.send_message(
messages.admin_config.format(cfg=st.admin_cfg), buttons=admin_btns
)
conv.cancel()
raise events.StopPropagation


@events.register(events.NewMessage(pattern=edit_user_btn))
@events.register(events.NewMessage(pattern=messages.edit_user_btn))
@admin_protect
async def edit_user_btn_handler(event: EventLike):
client: TelegramClient = event.client
Expand Down Expand Up @@ -62,14 +102,14 @@ async def edit_user_btn_handler(event: EventLike):
else:
ban_unban = messages.ban_user_btn

matrix = [
edit_user_kbd_matrix = [
[messages.cut_coins_btn, messages.reset_wallet_btn],
[ban_unban],
]

ask_choice = await conv.send_message(
messages.user_profile.format(heading="User Profile", user=user),
buttons=build_keyboard(matrix),
buttons=build_keyboard(edit_user_kbd_matrix),
)

user_choice_reply = await conv.get_response(ask_choice)
Expand Down Expand Up @@ -103,14 +143,14 @@ async def edit_user_btn_handler(event: EventLike):
)


@events.register(events.NewMessage(pattern=stats_btn))
@events.register(events.NewMessage(pattern=messages.stats_btn))
@admin_protect
async def stats_btn_handler(event: EventLike):
total = await st.engine.count(st.Person)
await event.respond(f"Total Number of Bot Users {total}")


@events.register(events.NewMessage(pattern=contact_dev_btn))
@events.register(events.NewMessage(pattern=messages.contact_dev_btn))
@admin_protect
async def contact_dev_btn_handler(event: EventLike):
await event.respond("Talk to @aahnikdaw for any issue.")
6 changes: 3 additions & 3 deletions refer_bot/handlers/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,11 +179,11 @@ async def get_link_handler(event: EventLike, user):
@events.register(events.NewMessage(pattern=messages.get_cash_btn))
@join_protect
async def get_cash_handler(event: EventLike, user: st.Person):
min_limit = 30
if user.coins < min_limit:
min_lim = st.admin_cfg.min_lim
if user.coins < min_lim:
msg = messages.not_sufficient_coins
else:
msg = messages.get_cash_text
await event.respond(
msg.format(min_limit=min_limit, admin=conf.CONTACT_ADMIN, uid=user.uid)
msg.format(min_limit=min_lim, admin=conf.CONTACT_ADMIN, uid=user.uid)
)
27 changes: 27 additions & 0 deletions refer_bot/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,16 @@
**🔀 Referals**: {user.ref_count}
"""

admin_config = """
List of **Force Channel** Links :
{cfg.force_channels_repr}
**Minimum Limit** for withdrawals: `{cfg.min_lim}`
**Value** of one **coin**: `{cfg.coin_val}`
"""

started_with_own_link = """
⚠️ You cant use your own link! Please share this with your friends.
"""
Expand Down Expand Up @@ -124,11 +134,28 @@

wallet_options = ["paytm", "phonepe"]

configure_btn = "🛠️ Configure"
edit_user_btn = "✏️ Edit User"
stats_btn = "📊 View Statistics"
contact_dev_btn = "🧑‍💻 Contact Developer"

admin_kbd_matrix = [[configure_btn, edit_user_btn], [stats_btn], [contact_dev_btn]]

cut_coins_btn = "✂️ Cut Coins"
reset_wallet_btn = "⚙️ Reset Wallet"
ban_user_btn = "🚫 Ban User"
unban_user_btn = "👍 Unban User"

edit_channels_btn = "Force Channels"
edit_min_lim_btn = "Minimum Limit"
edit_coin_val = "Coin Value"

admin_config_kbd_matrix = [
[edit_channels_btn],
[edit_min_lim_btn, edit_coin_val],
]


try:
from m2 import *

Expand Down
29 changes: 28 additions & 1 deletion refer_bot/storage.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import List, Optional

from odmantic import AIOEngine, Field, Model
from pydantic import StrictBool
from pydantic import StrictBool, validator

engine: AIOEngine = None

Expand All @@ -24,3 +24,30 @@ def ref_count(self):
@property
def wallet_str(self):
return (self.wallet + "(" + str(self.phone) + ")") if self.wallet else "Not set"


class AdminConfig(Model):
one_id: int = Field(primary_field=True)
force_channels: List[str] = []
min_lim: int = 0
coin_val: int = 0

@validator("force_channels")
def validate_delay(cls, val: List[str]):
for item in val:
if not item.startswith("https://t.me/"):
raise ValueError(f"`{item}` is an invalid link!")
return val

@property
def force_channels_repr(self):
if len(self.force_channels) == 0:
return "No channels set!"
string = "```"
for item in self.force_channels:
string += str(item) + "\n"
string += "```"
return string


admin_cfg: AdminConfig = None

0 comments on commit 9fbc54c

Please sign in to comment.