-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add caching and improve (fixes some bugs) (#16)
* Enhance caching logic for chat member retrieval - Implemented TTLCache for storing chat members with a 30-minute expiration. - Utilized caching to reduce API calls and improve performance. * improved code with reduced duplication * bump version
- Loading branch information
Showing
9 changed files
with
322 additions
and
202 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
__version__ = "2.4" | ||
__version__ = "2.5" |
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
from logging import getLogger | ||
from time import perf_counter | ||
from typing import Any | ||
|
||
from cachetools import TTLCache | ||
from cachetools.keys import hashkey | ||
|
||
LOGGER = getLogger(__name__) | ||
|
||
try: | ||
import pyrogram | ||
except ImportError: | ||
import hydrogram as pyrogram | ||
|
||
# Admins stay cached for 30 minutes | ||
member_cache = TTLCache(maxsize=512, ttl=(60 * 30), timer=perf_counter) | ||
|
||
|
||
async def get_member_with_cache( | ||
chat: pyrogram.types.Chat, | ||
user_id: int, | ||
force_reload: bool = False, | ||
) -> pyrogram.types.ChatMember | None | Any: | ||
""" | ||
Get a user from the cache, or fetch and cache them if they're not already cached. | ||
Args: | ||
chat (pyrogram.types.Chat): The chat to get the user from. | ||
user_id (int): The user ID to get. | ||
force_reload (bool): Whether to bypass the cache and reload the member. | ||
Returns: | ||
pyrogram.types.ChatMember | None | Any: The user, or None if they're not a participant or if an error occurred. | ||
""" | ||
cache_key = hashkey(chat.id, user_id) | ||
|
||
# Check if the member is in the cache and not forcing a reload | ||
if not force_reload and cache_key in member_cache: | ||
return member_cache[cache_key] | ||
|
||
try: | ||
member = await chat.get_member(user_id) | ||
except pyrogram.errors.UserNotParticipant: | ||
LOGGER.warning(f"User {user_id} is not a participant in chat {chat.id}.") | ||
return None | ||
except Exception as e: | ||
LOGGER.warning(f"Error found in get_member_with_cache for chat {chat.id}, user {user_id}: {e}") | ||
return None | ||
|
||
# Store in cache and return | ||
member_cache[cache_key] = member | ||
return member | ||
|
||
|
||
async def is_admin(member: pyrogram.types.ChatMember) -> bool: | ||
"""Check if the user is an admin in the chat.""" | ||
return member and member.status in {pyrogram.enums.ChatMemberStatus.OWNER, | ||
pyrogram.enums.ChatMemberStatus.ADMINISTRATOR} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
from hydrogram import Client | ||
from hydrogram.helpers import ikb | ||
from hydrogram.types import CallbackQuery, Message | ||
|
||
from Abg import * # type: ignore | ||
|
||
app = Client( | ||
name='Abg', | ||
api_id=6, | ||
api_hash='eb06d4abfb49dc3eeb1aeb98ae0f581e', | ||
bot_token="TOKEN", | ||
in_memory=True, | ||
) | ||
|
||
|
||
@app.on_cmd("start") | ||
async def start(self: Client, ctx: Message): | ||
""" | ||
Sends a Hello World message with an inline button that triggers the hello callback. | ||
""" | ||
await ctx.reply_text( | ||
"Hello World", | ||
reply_markup=ikb([[("Hello", "hello")]]) | ||
) | ||
|
||
|
||
@app.on_cb("hello") | ||
async def hello(_: Client, q: CallbackQuery): | ||
""" | ||
Called when the user presses the "Hello" button in the start command. | ||
""" | ||
await q.answer("Hello From Abg", show_alert=True) | ||
|
||
|
||
@app.on_cmd("del", group_only=True) | ||
@app.adminsOnly( | ||
permissions=["can_delete_messages", "can_restrict_members"], | ||
is_both=True, | ||
) | ||
async def del_msg(self: Client, m: Message): | ||
""" | ||
Deletes a message from the chat. | ||
If the message is a reply to another message, it deletes that message too. | ||
""" | ||
if m.reply_to_message: | ||
# Delete the replied message | ||
await self.delete_messages( | ||
chat_id=m.chat.id, | ||
message_ids=[m.reply_to_message.id], | ||
) | ||
# Delete the command message | ||
await m.delete() | ||
else: | ||
# If the message is not a reply, reply with an error message | ||
await m.reply_text(text="You need to reply to a message to delete it.", quote=True) | ||
|
||
|
||
if __name__ == "__main__": | ||
print("Running...") | ||
app.run() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters