Skip to content

Commit

Permalink
Replaced all single quotes with double quotes
Browse files Browse the repository at this point in the history
  • Loading branch information
smalyu committed Sep 22, 2024
1 parent 7366377 commit eb5d87f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 33 deletions.
28 changes: 14 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,11 @@ import asyncio
async def main():
# Initialize the message sender
sender = SenderMessages(
token='YOUR_TELEGRAM_BOT_TOKEN',
token="YOUR_TELEGRAM_BOT_TOKEN",
batch_size=30, # Increased batch size to 30 messages concurrently
delay_between_batches=1.5, # 1.5-second delay between batches
use_mongo=False, # No MongoDB logging
parse_mode='Markdown' # Setting parse_mode to Markdown
parse_mode="Markdown" # Setting parse_mode to Markdown
)

# Message text
Expand Down Expand Up @@ -92,11 +92,11 @@ import asyncio
async def main():
# Initialize the message sender
sender = SenderMessages(
token='YOUR_TELEGRAM_BOT_TOKEN',
token="YOUR_TELEGRAM_BOT_TOKEN",
batch_size=20, # Send 20 messages concurrently
delay_between_batches=2.0, # 2-second delay between batches
use_mongo=True, # Log results in MongoDB
parse_mode='HTML' # Using HTML as parse_mode
parse_mode="HTML" # Using HTML as parse_mode
)

# Prepare the data
Expand Down Expand Up @@ -132,7 +132,7 @@ import asyncio
async def main():
# Initialize the message sender
sender = SenderMessages(
token='YOUR_TELEGRAM_BOT_TOKEN',
token="YOUR_TELEGRAM_BOT_TOKEN",
batch_size=2, # Send 2 messages concurrently
delay_between_batches=1.5, # 1.5-second delay between batches
use_mongo=False # No MongoDB logging
Expand Down Expand Up @@ -172,12 +172,12 @@ import asyncio
async def main():
# Initialize the message sender with MongoDB logging
sender = SenderMessages(
token='YOUR_TELEGRAM_BOT_TOKEN',
token="YOUR_TELEGRAM_BOT_TOKEN",
batch_size=10, # Batch size of 10 messages
delay_between_batches=1.0, # 1-second delay between batches
use_mongo=True, # Enable MongoDB logging
mongo_uri='mongodb://localhost:27017', # MongoDB URI
mongo_db='telegram_logs' # Database name
mongo_uri="mongodb://localhost:27017", # MongoDB URI
mongo_db="telegram_logs" # Database name
)

# Message text
Expand Down Expand Up @@ -218,15 +218,15 @@ Here’s a simple function:
import requests
def get_photo_token(bot_token: str, photo_path: str, chat_id: int) -> str:
with open(photo_path, 'rb') as photo:
with open(photo_path, "rb") as photo:
response = requests.post(
url=f"https://api.telegram.org/bot{bot_token}/sendPhoto",
files={'photo': photo},
data={'chat_id': chat_id}
files={"photo": photo},
data={"chat_id": chat_id}
)
return response.json()['result']['photo'][-1]['file_id']
return response.json()["result"]["photo"][-1]["file_id"]
# Example usage:
# Replace 'YOUR_TELEGRAM_BOT_TOKEN' with your bot token and use your own chat_id or any user who interacted with the bot.
# photo_token = get_photo_token('YOUR_TELEGRAM_BOT_TOKEN', '/path/to/photo.jpg', YOUR_CHAT_ID)
# Replace "YOUR_TELEGRAM_BOT_TOKEN" with your bot token and use your own chat_id or any user who interacted with the bot.
# photo_token = get_photo_token("YOUR_TELEGRAM_BOT_TOKEN", "/path/to/photo.jpg", YOUR_CHAT_ID)
```
38 changes: 19 additions & 19 deletions sender_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@


class SenderMessages:
_url_template: str = 'https://api.telegram.org/bot{token}/{method}'
_url_template: str = "https://api.telegram.org/bot{token}/{method}"

def __init__(
self,
token: str,
batch_size: int = 25,
delay_between_batches: float = 1.1,
use_mongo: bool = True,
mongo_uri: str = 'mongodb://localhost:27017',
mongo_db: str = 'tg-bot-sender',
parse_mode: str = 'HTML'
mongo_uri: str = "mongodb://localhost:27017",
mongo_db: str = "tg-bot-sender",
parse_mode: str = "HTML"
):
self._token = token
self._batch_size = batch_size
Expand All @@ -44,11 +44,11 @@ async def run(
) -> (int, int):
"""Starts the message sending process."""
if photo_tokens and len(photo_tokens) > 1:
self._method = 'sendMediaGroup'
self._method = "sendMediaGroup"
elif photo_tokens and len(photo_tokens) == 1:
self._method = 'sendPhoto'
self._method = "sendPhoto"
else:
self._method = 'sendMessage'
self._method = "sendMessage"

self._url = self._url_template.format(token=self._token, method=self._method)
data = self._prepare_data(text, photo_tokens, reply_markup)
Expand All @@ -59,31 +59,31 @@ async def run(

def _prepare_data(self, text: str, photo_tokens: list[str] | None, reply_markup: dict | None) -> dict:
"""Prepares data for sending based on the method."""
if self._method == 'sendMediaGroup':
if self._method == "sendMediaGroup":
media = []
for i, photo_token in enumerate(photo_tokens):
item = {'type': 'photo', 'media': photo_token}
item = {"type": "photo", "media": photo_token}
if i == 0:
item['caption'] = text
item['parse_mode'] = self._parse_mode
item["caption"] = text
item["parse_mode"] = self._parse_mode
media.append(item)
data = {'media': json.dumps(media)}
data = {"media": json.dumps(media)}
if reply_markup:
logger.warning("reply_markup is not supported in sendMediaGroup")
elif self._method == 'sendPhoto':
data = {'photo': photo_tokens[0], 'caption': text, 'parse_mode': self._parse_mode}
elif self._method == "sendPhoto":
data = {"photo": photo_tokens[0], "caption": text, "parse_mode": self._parse_mode}
if reply_markup:
data['reply_markup'] = json.dumps(reply_markup)
data["reply_markup"] = json.dumps(reply_markup)
else: # sendMessage
data = {'text': text, 'parse_mode': self._parse_mode}
data = {"text": text, "parse_mode": self._parse_mode}
if reply_markup:
data['reply_markup'] = json.dumps(reply_markup)
data["reply_markup"] = json.dumps(reply_markup)
return data

def _get_collection_name(self) -> str:
"""Creates a unique name for the MongoDB collection using Moscow time."""
moscow_time = time.gmtime(time.time() + 3 * 60 * 60)
return time.strftime('%d_%m_%Y__%H_%M_%S', moscow_time)
return time.strftime("%d_%m_%Y__%H_%M_%S", moscow_time)

async def _send_messages(self, data: dict, chat_ids: list[int]) -> (int, int):
"""Starts the message sending process with logging."""
Expand All @@ -98,7 +98,7 @@ def _create_send_batches(self, data: dict, chat_ids: list[int], session: ClientS

for chat_id in chat_ids:
data_with_id = data.copy()
data_with_id['chat_id'] = chat_id
data_with_id["chat_id"] = chat_id
current_batch.append(self._send_message(data_with_id, session))
if len(current_batch) >= self._batch_size:
batches.append(current_batch)
Expand Down

0 comments on commit eb5d87f

Please sign in to comment.