···
# When run directly by zulip-bots, add the package to path
src_dir = Path(__file__).parent.parent.parent
if str(src_dir) not in sys.path:
sys.path.insert(0, str(src_dir))
···
self._send_help(message, bot_handler)
elif command == "status":
self._send_status(message, bot_handler, sender)
137
-
elif command == "sync" and len(command_parts) > 1 and command_parts[1] == "now":
140
+
and len(command_parts) > 1
141
+
and command_parts[1] == "now"
self._handle_force_sync(message, bot_handler, sender)
self._handle_reset_command(message, bot_handler, sender)
elif command == "config":
142
-
self._handle_config_command(message, bot_handler, command_parts[1:], sender)
147
+
self._handle_config_command(
148
+
message, bot_handler, command_parts[1:], sender
elif command == "schedule":
self._handle_schedule_command(message, bot_handler, sender)
146
-
self._handle_claim_command(message, bot_handler, command_parts[1:], sender)
153
+
self._handle_claim_command(
154
+
message, bot_handler, command_parts[1:], sender
148
-
bot_handler.send_reply(message, f"Unknown command: {command}. Type `@mention help` for usage.")
157
+
bot_handler.send_reply(
159
+
f"Unknown command: {command}. Type `@mention help` for usage.",
self.logger.error(f"Error handling command '{command}': {e}")
bot_handler.send_reply(message, f"Error processing command: {str(e)}")
···
# Get bot's actual name from Zulip
bot_info = bot_handler._client.get_profile()
158
-
if bot_info.get('result') == 'success':
159
-
bot_name = bot_info.get('full_name', '').lower()
170
+
if bot_info.get("result") == "success":
171
+
bot_name = bot_info.get("full_name", "").lower()
161
-
return f"@{bot_name}" in content.lower() or f"@**{bot_name}**" in content.lower()
174
+
f"@{bot_name}" in content.lower()
175
+
or f"@**{bot_name}**" in content.lower()
self.logger.debug(f"Could not get bot profile: {e}")
···
# Get bot's actual name from Zulip
bot_info = bot_handler._client.get_profile()
175
-
if bot_info.get('result') == 'success':
176
-
bot_name = bot_info.get('full_name', '')
190
+
if bot_info.get("result") == "success":
191
+
bot_name = bot_info.get("full_name", "")
# Remove @bot_name or @**bot_name**
escaped_name = re.escape(bot_name)
180
-
content = re.sub(rf'@(?:\*\*)?{escaped_name}(?:\*\*)?', '', content, flags=re.IGNORECASE).strip()
196
+
rf"@(?:\*\*)?{escaped_name}(?:\*\*)?",
199
+
flags=re.IGNORECASE,
self.logger.debug(f"Could not get bot profile for mention cleaning: {e}")
# Fallback to removing @thicket
186
-
content = re.sub(r'@(?:\*\*)?thicket(?:\*\*)?', '', content, flags=re.IGNORECASE).strip()
207
+
r"@(?:\*\*)?thicket(?:\*\*)?", "", content, flags=re.IGNORECASE
def _send_help(self, message: dict[str, Any], bot_handler: BotHandler) -> None:
bot_handler.send_reply(message, self.usage())
193
-
def _send_status(self, message: dict[str, Any], bot_handler: BotHandler, sender: str) -> None:
216
+
self, message: dict[str, Any], bot_handler: BotHandler, sender: str
"""Send bot status information."""
f"**Thicket Bot Status** (requested by {sender})",
···
202
-
status_lines.extend([
203
-
"🐛 **Debug Mode:** ENABLED",
204
-
f"🎯 **Debug User:** {self.debug_user}",
226
+
status_lines.extend(
228
+
"🐛 **Debug Mode:** ENABLED",
229
+
f"🎯 **Debug User:** {self.debug_user}",
208
-
status_lines.extend([
209
-
f"📍 **Stream:** {self.stream_name or 'Not configured'}",
210
-
f"📝 **Topic:** {self.topic_name or 'Not configured'}",
234
+
status_lines.extend(
236
+
f"📍 **Stream:** {self.stream_name or 'Not configured'}",
237
+
f"📝 **Topic:** {self.topic_name or 'Not configured'}",
214
-
status_lines.extend([
215
-
f"⏱️ **Sync Interval:** {self.sync_interval}s ({self.sync_interval // 60}m {self.sync_interval % 60}s)",
216
-
f"📊 **Max Entries/Sync:** {self.max_entries_per_sync}",
217
-
f"📁 **Config Path:** {self.config_path or 'Not configured'}",
219
-
f"📄 **Tracked Entries:** {len(self.posted_entries)}",
220
-
f"🔄 **Catchup Mode:** {'Active (first run)' if len(self.posted_entries) == 0 else 'Inactive'}",
221
-
f"✅ **Thicket Initialized:** {'Yes' if self.git_store else 'No'}",
223
-
self._get_schedule_info(),
242
+
status_lines.extend(
244
+
f"⏱️ **Sync Interval:** {self.sync_interval}s ({self.sync_interval // 60}m {self.sync_interval % 60}s)",
245
+
f"📊 **Max Entries/Sync:** {self.max_entries_per_sync}",
246
+
f"📁 **Config Path:** {self.config_path or 'Not configured'}",
248
+
f"📄 **Tracked Entries:** {len(self.posted_entries)}",
249
+
f"🔄 **Catchup Mode:** {'Active (first run)' if len(self.posted_entries) == 0 else 'Inactive'}",
250
+
f"✅ **Thicket Initialized:** {'Yes' if self.git_store else 'No'}",
252
+
self._get_schedule_info(),
bot_handler.send_reply(message, "\n".join(status_lines))
228
-
def _handle_force_sync(self, message: dict[str, Any], bot_handler: BotHandler, sender: str) -> None:
258
+
def _handle_force_sync(
259
+
self, message: dict[str, Any], bot_handler: BotHandler, sender: str
"""Handle immediate sync request."""
if not self._check_initialization(message, bot_handler):
233
-
bot_handler.send_reply(message, f"🔄 Starting immediate sync... (requested by {sender})")
265
+
bot_handler.send_reply(
266
+
message, f"🔄 Starting immediate sync... (requested by {sender})"
new_entries = self._perform_sync(bot_handler)
239
-
f"✅ Sync completed! Found {len(new_entries)} new entries."
272
+
message, f"✅ Sync completed! Found {len(new_entries)} new entries."
self.logger.error(f"Force sync failed: {e}")
bot_handler.send_reply(message, f"❌ Sync failed: {str(e)}")
245
-
def _handle_reset_command(self, message: dict[str, Any], bot_handler: BotHandler, sender: str) -> None:
278
+
def _handle_reset_command(
279
+
self, message: dict[str, Any], bot_handler: BotHandler, sender: str
"""Handle reset command to clear posted entries tracking."""
self.posted_entries.clear()
self._save_posted_entries(bot_handler)
252
-
f"✅ Posting history reset! Recent entries will be posted on next sync. (requested by {sender})"
287
+
f"✅ Posting history reset! Recent entries will be posted on next sync. (requested by {sender})",
self.logger.info(f"Posted entries tracking reset by {sender}")
self.logger.error(f"Reset failed: {e}")
bot_handler.send_reply(message, f"❌ Reset failed: {str(e)}")
259
-
def _handle_schedule_command(self, message: dict[str, Any], bot_handler: BotHandler, sender: str) -> None:
294
+
def _handle_schedule_command(
295
+
self, message: dict[str, Any], bot_handler: BotHandler, sender: str
"""Handle schedule query command."""
schedule_info = self._get_schedule_info()
264
-
f"**Thicket Bot Schedule** (requested by {sender})\n\n{schedule_info}"
301
+
f"**Thicket Bot Schedule** (requested by {sender})\n\n{schedule_info}",
def _handle_claim_command(
···
"""Handle username claiming command."""
···
sender_email = message.get("sender_email")
if not sender_user_id or not sender_email:
289
-
bot_handler.send_reply(message, "❌ Could not determine your Zulip user information.")
326
+
bot_handler.send_reply(
327
+
message, "❌ Could not determine your Zulip user information."
···
server_url = zulip_site_url.replace("https://", "").replace("http://", "")
298
-
bot_handler.send_reply(message, "❌ Could not determine Zulip server URL.")
337
+
bot_handler.send_reply(
338
+
message, "❌ Could not determine Zulip server URL."
# Check if username exists in thicket
···
306
-
f"❌ Username `{username}` not found in thicket. Available users: {', '.join(self.git_store.list_users())}"
347
+
f"❌ Username `{username}` not found in thicket. Available users: {', '.join(self.git_store.list_users())}",
···
existing_zulip_id = user.get_zulip_mention(server_url)
# Check if it's claimed by the same user
314
-
if existing_zulip_id == sender_email or str(existing_zulip_id) == str(sender_user_id):
355
+
if existing_zulip_id == sender_email or str(existing_zulip_id) == str(
317
-
f"✅ Username `{username}` is already claimed by you on {server_url}!"
360
+
f"✅ Username `{username}` is already claimed by you on {server_url}!",
322
-
f"❌ Username `{username}` is already claimed by another user on {server_url}."
365
+
f"❌ Username `{username}` is already claimed by another user on {server_url}.",
# Claim the username - prefer email for consistency
327
-
success = self.git_store.add_zulip_association(username, server_url, sender_email)
370
+
success = self.git_store.add_zulip_association(
371
+
username, server_url, sender_email
330
-
reply_msg = f"🎉 Successfully claimed username `{username}` for **{sender}** on {server_url}!\n" + \
331
-
"You will now be mentioned when new articles are posted from this user's feeds."
376
+
f"🎉 Successfully claimed username `{username}` for **{sender}** on {server_url}!\n"
377
+
+ "You will now be mentioned when new articles are posted from this user's feeds."
bot_handler.send_reply(message, reply_msg)
# Send notification to configured stream if enabled and not in debug mode
335
-
if (self.username_claim_notifications and
336
-
not self.debug_user and
337
-
self.stream_name and self.topic_name):
383
+
self.username_claim_notifications
384
+
and not self.debug_user
385
+
and self.stream_name
386
+
and self.topic_name
notification_msg = f"👋 **{sender}** claimed thicket username `{username}` on {server_url}"
340
-
bot_handler.send_message({
342
-
"to": self.stream_name,
343
-
"subject": self.topic_name,
344
-
"content": notification_msg
390
+
bot_handler.send_message(
393
+
"to": self.stream_name,
394
+
"subject": self.topic_name,
395
+
"content": notification_msg,
347
-
self.logger.error(f"Failed to send username claim notification: {e}")
400
+
f"Failed to send username claim notification: {e}"
349
-
self.logger.info(f"User {sender} ({sender_email}) claimed username {username} on {server_url}")
404
+
f"User {sender} ({sender_email}) claimed username {username} on {server_url}"
353
-
f"❌ Failed to claim username `{username}`. This shouldn't happen - please contact an administrator."
409
+
f"❌ Failed to claim username `{username}`. This shouldn't happen - please contact an administrator.",
···
"""Handle configuration commands."""
369
-
bot_handler.send_reply(message, "Usage: `@mention config <setting> <value>`")
425
+
bot_handler.send_reply(
426
+
message, "Usage: `@mention config <setting> <value>`"
setting = args[0].lower()
···
old_value = self.stream_name
self._save_bot_config(bot_handler)
379
-
bot_handler.send_reply(message, f"✅ Stream set to: **{value}** (by {sender})")
380
-
self._send_config_change_notification(bot_handler, sender, "stream", old_value, value)
437
+
bot_handler.send_reply(
438
+
message, f"✅ Stream set to: **{value}** (by {sender})"
440
+
self._send_config_change_notification(
441
+
bot_handler, sender, "stream", old_value, value
old_value = self.topic_name
self._save_bot_config(bot_handler)
386
-
bot_handler.send_reply(message, f"✅ Topic set to: **{value}** (by {sender})")
387
-
self._send_config_change_notification(bot_handler, sender, "topic", old_value, value)
448
+
bot_handler.send_reply(
449
+
message, f"✅ Topic set to: **{value}** (by {sender})"
451
+
self._send_config_change_notification(
452
+
bot_handler, sender, "topic", old_value, value
elif setting == "interval":
393
-
bot_handler.send_reply(message, "❌ Interval must be at least 60 seconds")
459
+
bot_handler.send_reply(
460
+
message, "❌ Interval must be at least 60 seconds"
old_value = self.sync_interval
self.sync_interval = interval
self._save_bot_config(bot_handler)
398
-
bot_handler.send_reply(message, f"✅ Sync interval set to: **{interval}s** (by {sender})")
399
-
self._send_config_change_notification(bot_handler, sender, "sync interval", f"{old_value}s", f"{interval}s")
466
+
bot_handler.send_reply(
467
+
message, f"✅ Sync interval set to: **{interval}s** (by {sender})"
469
+
self._send_config_change_notification(
401
-
bot_handler.send_reply(message, "❌ Invalid interval value. Must be a number of seconds.")
477
+
bot_handler.send_reply(
478
+
message, "❌ Invalid interval value. Must be a number of seconds."
elif setting == "max_entries":
if max_entries < 1 or max_entries > 50:
407
-
bot_handler.send_reply(message, "❌ Max entries must be between 1 and 50")
485
+
bot_handler.send_reply(
486
+
message, "❌ Max entries must be between 1 and 50"
old_value = self.max_entries_per_sync
self.max_entries_per_sync = max_entries
self._save_bot_config(bot_handler)
412
-
bot_handler.send_reply(message, f"✅ Max entries per sync set to: **{max_entries}** (by {sender})")
413
-
self._send_config_change_notification(bot_handler, sender, "max entries per sync", str(old_value), str(max_entries))
492
+
bot_handler.send_reply(
494
+
f"✅ Max entries per sync set to: **{max_entries}** (by {sender})",
496
+
self._send_config_change_notification(
499
+
"max entries per sync",
415
-
bot_handler.send_reply(message, "❌ Invalid max entries value. Must be a number.")
504
+
bot_handler.send_reply(
505
+
message, "❌ Invalid max entries value. Must be a number."
420
-
f"❌ Unknown setting: {setting}. Available: stream, topic, interval, max_entries"
511
+
f"❌ Unknown setting: {setting}. Available: stream, topic, interval, max_entries",
def _load_bot_config(self, bot_handler: BotHandler) -> None:
···
bot_section = config["bot"]
self.sync_interval = bot_section.getint("sync_interval", 300)
469
-
self.max_entries_per_sync = bot_section.getint("max_entries_per_sync", 10)
560
+
self.max_entries_per_sync = bot_section.getint(
561
+
"max_entries_per_sync", 10
self.rate_limit_delay = bot_section.getint("rate_limit_delay", 5)
self.posts_per_batch = bot_section.getint("posts_per_batch", 5)
···
if "notifications" in config:
notifications_section = config["notifications"]
487
-
self.config_change_notifications = notifications_section.getboolean("config_change_notifications", True)
488
-
self.username_claim_notifications = notifications_section.getboolean("username_claim_notifications", True)
580
+
self.config_change_notifications = notifications_section.getboolean(
581
+
"config_change_notifications", True
583
+
self.username_claim_notifications = notifications_section.getboolean(
584
+
"username_claim_notifications", True
self.logger.info(f"Loaded configuration from {botrc_path}")
···
# Load thicket configuration
with open(self.config_path) as f:
config_data = yaml.safe_load(f)
self.config = ThicketConfig(**config_data)
···
zulip_user_id = user.get_zulip_mention(server_url)
532
-
raise ValueError(f"User '{self.debug_user}' has no Zulip association for server '{server_url}'")
631
+
f"User '{self.debug_user}' has no Zulip association for server '{server_url}'"
# Try to look up the actual Zulip user ID from the email address
# But don't fail if we can't - we'll try again when sending messages
···
if actual_user_id and actual_user_id != zulip_user_id:
# Successfully resolved to numeric ID
self.debug_zulip_user_id = actual_user_id
540
-
self.logger.info(f"Debug mode enabled: Will send DMs to {self.debug_user} (email: {zulip_user_id}, user_id: {actual_user_id}) on {server_url}")
641
+
f"Debug mode enabled: Will send DMs to {self.debug_user} (email: {zulip_user_id}, user_id: {actual_user_id}) on {server_url}"
# Keep the email address, will resolve later when sending
self.debug_zulip_user_id = zulip_user_id
544
-
self.logger.info(f"Debug mode enabled: Will send DMs to {self.debug_user} ({zulip_user_id}) on {server_url} (will resolve user ID when sending)")
647
+
f"Debug mode enabled: Will send DMs to {self.debug_user} ({zulip_user_id}) on {server_url} (will resolve user ID when sending)"
546
-
def _lookup_zulip_user_id(self, bot_handler: BotHandler, email_or_id: str) -> Optional[str]:
650
+
def _lookup_zulip_user_id(
651
+
self, bot_handler: BotHandler, email_or_id: str
652
+
) -> Optional[str]:
"""Look up Zulip user ID from email address or return the ID if it's already numeric."""
# If it's already a numeric user ID, return it
if email_or_id.isdigit():
···
# First try the get_user_by_email API if available
user_result = client.get_user_by_email(email_or_id)
561
-
if user_result.get('result') == 'success':
562
-
user_data = user_result.get('user', {})
563
-
user_id = user_data.get('user_id')
667
+
if user_result.get("result") == "success":
668
+
user_data = user_result.get("user", {})
669
+
user_id = user_data.get("user_id")
565
-
self.logger.info(f"Found user ID {user_id} for '{email_or_id}' via get_user_by_email API")
672
+
f"Found user ID {user_id} for '{email_or_id}' via get_user_by_email API"
except (AttributeError, Exception):
# Fallback: Get all users and search through them
users_result = client.get_users()
572
-
if users_result.get('result') == 'success':
573
-
for user in users_result['members']:
574
-
user_email = user.get('email', '')
575
-
delivery_email = user.get('delivery_email', '')
680
+
if users_result.get("result") == "success":
681
+
for user in users_result["members"]:
682
+
user_email = user.get("email", "")
683
+
delivery_email = user.get("delivery_email", "")
577
-
if (user_email == email_or_id or
578
-
delivery_email == email_or_id or
579
-
str(user.get('user_id')) == email_or_id):
580
-
user_id = user.get('user_id')
686
+
user_email == email_or_id
687
+
or delivery_email == email_or_id
688
+
or str(user.get("user_id")) == email_or_id
690
+
user_id = user.get("user_id")
583
-
self.logger.error(f"No user found with identifier '{email_or_id}'. Searched {len(users_result['members'])} users.")
694
+
f"No user found with identifier '{email_or_id}'. Searched {len(users_result['members'])} users."
586
-
self.logger.error(f"Failed to get users: {users_result.get('msg', 'Unknown error')}")
699
+
f"Failed to get users: {users_result.get('msg', 'Unknown error')}"
self.logger.error(f"Error looking up user ID for '{email_or_id}': {e}")
593
-
def _lookup_zulip_user_info(self, bot_handler: BotHandler, email_or_id: str) -> tuple[Optional[str], Optional[str]]:
707
+
def _lookup_zulip_user_info(
708
+
self, bot_handler: BotHandler, email_or_id: str
709
+
) -> tuple[Optional[str], Optional[str]]:
"""Look up both Zulip user ID and full name from email address."""
if email_or_id.isdigit():
···
# Try get_user_by_email API first
user_result = client.get_user_by_email(email_or_id)
606
-
if user_result.get('result') == 'success':
607
-
user_data = user_result.get('user', {})
608
-
user_id = user_data.get('user_id')
609
-
full_name = user_data.get('full_name', '')
722
+
if user_result.get("result") == "success":
723
+
user_data = user_result.get("user", {})
724
+
user_id = user_data.get("user_id")
725
+
full_name = user_data.get("full_name", "")
return str(user_id), full_name
···
# Fallback: search all users
users_result = client.get_users()
617
-
if users_result.get('result') == 'success':
618
-
for user in users_result['members']:
619
-
if (user.get('email') == email_or_id or
620
-
user.get('delivery_email') == email_or_id):
621
-
return str(user.get('user_id')), user.get('full_name', '')
733
+
if users_result.get("result") == "success":
734
+
for user in users_result["members"]:
736
+
user.get("email") == email_or_id
737
+
or user.get("delivery_email") == email_or_id
739
+
return str(user.get("user_id")), user.get("full_name", "")
···
def _save_posted_entries(self, bot_handler: BotHandler) -> None:
"""Save the set of posted entries."""
642
-
bot_handler.storage.put("posted_entries", json.dumps(list(self.posted_entries)))
760
+
bot_handler.storage.put(
761
+
"posted_entries", json.dumps(list(self.posted_entries))
self.logger.error(f"Error saving posted entries: {e}")
646
-
def _check_initialization(self, message: dict[str, Any], bot_handler: BotHandler) -> bool:
766
+
def _check_initialization(
767
+
self, message: dict[str, Any], bot_handler: BotHandler
"""Check if thicket is properly initialized."""
if not self.git_store or not self.config:
651
-
"❌ Thicket not initialized. Please check configuration."
772
+
message, "❌ Thicket not initialized. Please check configuration."
···
if not self.stream_name or not self.topic_name:
662
-
"❌ Stream and topic must be configured first. Use `@mention config stream <name>` and `@mention config topic <name>`"
783
+
"❌ Stream and topic must be configured first. Use `@mention config stream <name>` and `@mention config topic <name>`",
···
def _schedule_sync(self, bot_handler: BotHandler) -> None:
"""Schedule periodic sync operations."""
674
-
can_sync = (self.git_store and
675
-
((self.stream_name and self.topic_name) or
796
+
can_sync = self.git_store and (
797
+
(self.stream_name and self.topic_name) or self.debug_user
self._perform_sync(bot_handler)
···
# Start background thread
sync_thread = threading.Thread(target=sync_loop, daemon=True)
···
asyncio.set_event_loop(loop)
new_count, _ = loop.run_until_complete(
711
-
sync_feed(self.git_store, username, str(feed_url), dry_run=False)
835
+
self.git_store, username, str(feed_url), dry_run=False
# Get the newly added entries
718
-
entries_to_check = self.git_store.list_entries(username, limit=new_count)
843
+
entries_to_check = self.git_store.list_entries(
844
+
username, limit=new_count
# Always check for catchup mode on first run
# Catchup mode: get configured number of entries on first run
723
-
catchup_entries = self.git_store.list_entries(username, limit=self.catchup_entries)
724
-
entries_to_check = catchup_entries if not entries_to_check else entries_to_check
850
+
catchup_entries = self.git_store.list_entries(
851
+
username, limit=self.catchup_entries
853
+
entries_to_check = (
855
+
if not entries_to_check
856
+
else entries_to_check
for entry in entries_to_check:
entry_key = f"{username}:{entry.id}"
···
737
-
self.logger.error(f"Error syncing feed {feed_url} for user {username}: {e}")
871
+
f"Error syncing feed {feed_url} for user {username}: {e}"
if len(new_entries) >= self.max_entries_per_sync:
···
# Rate limiting: pause after configured number of messages
752
-
if posted_count % self.posts_per_batch == 0 and i < len(new_entries) - 1:
888
+
posted_count % self.posts_per_batch == 0
889
+
and i < len(new_entries) - 1
time.sleep(self.rate_limit_delay)
self._save_posted_entries(bot_handler)
···
return [entry for entry, _ in new_entries]
762
-
def _post_entry_to_zulip(self, entry: AtomEntry, bot_handler: BotHandler, username: str) -> None:
900
+
def _post_entry_to_zulip(
901
+
self, entry: AtomEntry, bot_handler: BotHandler, username: str
"""Post a single entry to the configured Zulip stream/topic or debug user DM."""
# Get current Zulip server from environment
···
zulip_user_id = user.get_zulip_mention(server_url)
# Look up the actual Zulip full name for proper @mention
777
-
_, zulip_full_name = self._lookup_zulip_user_info(bot_handler, zulip_user_id)
917
+
_, zulip_full_name = self._lookup_zulip_user_info(
918
+
bot_handler, zulip_user_id
display_name = zulip_full_name or user.display_name or username
# Check if author is different from the user - avoid redundancy
···
789
-
published_info = f" • {entry.published.strftime('%Y-%m-%d')}"
932
+
f" • {entry.published.strftime('%Y-%m-%d')}"
mention_info = f"@**{display_name}** posted{author_info}{published_info}:\n\n"
···
published_info = f" • {entry.published.strftime('%Y-%m-%d')}"
808
-
mention_info = f"**{display_name}** posted{author_info}{published_info}:\n\n"
953
+
f"**{display_name}** posted{author_info}{published_info}:\n\n"
# Format the message with HTML processing
···
user_id_to_use = self.debug_zulip_user_id
if not user_id_to_use.isdigit():
# Need to look up the numeric ID
834
-
resolved_id = self._lookup_zulip_user_id(bot_handler, user_id_to_use)
980
+
resolved_id = self._lookup_zulip_user_id(
981
+
bot_handler, user_id_to_use
user_id_to_use = resolved_id
837
-
self.logger.debug(f"Resolved {self.debug_zulip_user_id} to user ID {user_id_to_use}")
986
+
f"Resolved {self.debug_zulip_user_id} to user ID {user_id_to_use}"
839
-
self.logger.error(f"Could not resolve user ID for {self.debug_zulip_user_id}")
990
+
f"Could not resolve user ID for {self.debug_zulip_user_id}"
# For private messages, user_id needs to be an integer, not string
user_id_int = int(user_id_to_use)
845
-
bot_handler.send_message({
847
-
"to": [user_id_int], # Use integer user ID
848
-
"content": debug_message
997
+
bot_handler.send_message(
1000
+
"to": [user_id_int], # Use integer user ID
1001
+
"content": debug_message,
# If conversion to int fails, user_id_to_use might be an email
853
-
bot_handler.send_message({
855
-
"to": [user_id_to_use], # Try as string (email)
856
-
"content": debug_message
1007
+
bot_handler.send_message(
1009
+
"type": "private",
1010
+
"to": [user_id_to_use], # Try as string (email)
1011
+
"content": debug_message,
859
-
self.logger.error(f"Failed to send DM to {self.debug_user} (tried both int and string): {e2}")
1015
+
self.logger.error(
1016
+
f"Failed to send DM to {self.debug_user} (tried both int and string): {e2}"
862
-
self.logger.error(f"Failed to send DM to {self.debug_user} ({user_id_to_use}): {e}")
1020
+
self.logger.error(
1021
+
f"Failed to send DM to {self.debug_user} ({user_id_to_use}): {e}"
864
-
self.logger.info(f"Posted entry to debug user {self.debug_user}: {entry.title}")
1025
+
f"Posted entry to debug user {self.debug_user}: {entry.title}"
# Normal mode: send to stream/topic
867
-
bot_handler.send_message({
869
-
"to": self.stream_name,
870
-
"subject": self.topic_name,
871
-
"content": message_content
873
-
self.logger.info(f"Posted entry to stream: {entry.title} (user: {username})")
1029
+
bot_handler.send_message(
1032
+
"to": self.stream_name,
1033
+
"subject": self.topic_name,
1034
+
"content": message_content,
1038
+
f"Posted entry to stream: {entry.title} (user: {username})"
self.logger.error(f"Error posting entry to Zulip: {e}")
···
heading_style="ATX", # Use # for headings (but we'll post-process these)
bullets="-", # Use - for bullets
892
-
convert=['a', 'b', 'strong', 'i', 'em', 'code', 'pre', 'p', 'br', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
# Post-process to convert headings to bold for compact summaries
# Convert markdown headers to bold with period
898
-
markdown = re.sub(r'^#{1,6}\s*(.+)$', r'**\1.**', markdown, flags=re.MULTILINE)
1084
+
markdown = re.sub(
1085
+
r"^#{1,6}\s*(.+)$", r"**\1.**", markdown, flags=re.MULTILINE
# Clean up excessive newlines and make more compact
901
-
markdown = re.sub(r'\n\s*\n\s*\n+', ' ', markdown) # Multiple newlines become space
902
-
markdown = re.sub(r'\n\s*\n', '. ', markdown) # Double newlines become sentence breaks
903
-
markdown = re.sub(r'\n', ' ', markdown) # Single newlines become spaces
1089
+
markdown = re.sub(
1090
+
r"\n\s*\n\s*\n+", " ", markdown
1091
+
) # Multiple newlines become space
1092
+
markdown = re.sub(
1093
+
r"\n\s*\n", ". ", markdown
1094
+
) # Double newlines become sentence breaks
1095
+
markdown = re.sub(r"\n", " ", markdown) # Single newlines become spaces
# Clean up double periods and excessive whitespace
906
-
markdown = re.sub(r'\.\.+', '.', markdown)
907
-
markdown = re.sub(r'\s+', ' ', markdown)
1098
+
markdown = re.sub(r"\.\.+", ".", markdown)
1099
+
markdown = re.sub(r"\s+", " ", markdown)
# Fallback: manual HTML processing
# Convert headings to bold with periods for compact summaries
916
-
content = re.sub(r'<h[1-6](?:\s[^>]*)?>([^<]*)</h[1-6]>', r'**\1.** ', content, flags=re.IGNORECASE)
1110
+
r"<h[1-6](?:\s[^>]*)?>([^<]*)</h[1-6]>",
1113
+
flags=re.IGNORECASE,
# Convert common HTML elements to Markdown
919
-
content = re.sub(r'<(?:strong|b)(?:\s[^>]*)?>([^<]*)</(?:strong|b)>', r'**\1**', content, flags=re.IGNORECASE)
920
-
content = re.sub(r'<(?:em|i)(?:\s[^>]*)?>([^<]*)</(?:em|i)>', r'*\1*', content, flags=re.IGNORECASE)
921
-
content = re.sub(r'<code(?:\s[^>]*)?>([^<]*)</code>', r'`\1`', content, flags=re.IGNORECASE)
922
-
content = re.sub(r'<a(?:\s[^>]*?)?\s*href=["\']([^"\']*)["\'](?:\s[^>]*)?>([^<]*)</a>', r'[\2](\1)', content, flags=re.IGNORECASE)
1118
+
r"<(?:strong|b)(?:\s[^>]*)?>([^<]*)</(?:strong|b)>",
1121
+
flags=re.IGNORECASE,
1124
+
r"<(?:em|i)(?:\s[^>]*)?>([^<]*)</(?:em|i)>",
1127
+
flags=re.IGNORECASE,
1130
+
r"<code(?:\s[^>]*)?>([^<]*)</code>",
1133
+
flags=re.IGNORECASE,
1136
+
r'<a(?:\s[^>]*?)?\s*href=["\']([^"\']*)["\'](?:\s[^>]*)?>([^<]*)</a>',
1139
+
flags=re.IGNORECASE,
# Convert block elements to spaces instead of newlines for compactness
925
-
content = re.sub(r'<br\s*/?>', ' ', content, flags=re.IGNORECASE)
926
-
content = re.sub(r'</p>\s*<p>', '. ', content, flags=re.IGNORECASE)
927
-
content = re.sub(r'</?(?:p|div)(?:\s[^>]*)?>', ' ', content, flags=re.IGNORECASE)
1143
+
content = re.sub(r"<br\s*/?>", " ", content, flags=re.IGNORECASE)
1144
+
content = re.sub(r"</p>\s*<p>", ". ", content, flags=re.IGNORECASE)
1146
+
r"</?(?:p|div)(?:\s[^>]*)?>", " ", content, flags=re.IGNORECASE
# Remove remaining HTML tags
930
-
content = re.sub(r'<[^>]+>', '', content)
1150
+
content = re.sub(r"<[^>]+>", "", content)
# Clean up whitespace and make compact
933
-
content = re.sub(r'\s+', ' ', content) # Multiple whitespace becomes single space
934
-
content = re.sub(r'\.\.+', '.', content) # Multiple periods become single period
1154
+
r"\s+", " ", content
1155
+
) # Multiple whitespace becomes single space
1157
+
r"\.\.+", ".", content
1158
+
) # Multiple periods become single period
self.logger.error(f"Error processing HTML content: {e}")
# Last resort: just strip HTML tags
941
-
return re.sub(r'<[^>]+>', '', html_content).strip()
1166
+
return re.sub(r"<[^>]+>", "", html_content).strip()
def _get_schedule_info(self) -> str:
"""Get schedule information string."""
···
last_sync = datetime.datetime.fromtimestamp(self.last_sync_time)
next_sync = last_sync + datetime.timedelta(seconds=self.sync_interval)
now = datetime.datetime.now()
···
968
-
f"🕐 **Last Sync:** {last_sync.strftime('%H:%M:%S')}",
969
-
f"⏰ **Next Sync:** {next_sync.strftime('%H:%M:%S')} (in {time_str})",
1195
+
f"🕐 **Last Sync:** {last_sync.strftime('%H:%M:%S')}",
1196
+
f"⏰ **Next Sync:** {next_sync.strftime('%H:%M:%S')} (in {time_str})",
973
-
f"🕐 **Last Sync:** {last_sync.strftime('%H:%M:%S')}",
974
-
f"⏰ **Next Sync:** Due now (running every {self.sync_interval}s)",
1202
+
f"🕐 **Last Sync:** {last_sync.strftime('%H:%M:%S')}",
1203
+
f"⏰ **Next Sync:** Due now (running every {self.sync_interval}s)",
lines.append("🕐 **Last Sync:** Never (bot starting up)")
# Add sync frequency info
if self.sync_interval >= 3600:
981
-
frequency_str = f"{self.sync_interval // 3600}h {(self.sync_interval % 3600) // 60}m"
1212
+
f"{self.sync_interval // 3600}h {(self.sync_interval % 3600) // 60}m"
elif self.sync_interval >= 60:
frequency_str = f"{self.sync_interval // 60}m {self.sync_interval % 60}s"
···
991
-
def _send_config_change_notification(self, bot_handler: BotHandler, changer: str, setting: str, old_value: Optional[str], new_value: str) -> None:
1223
+
def _send_config_change_notification(
1225
+
bot_handler: BotHandler,
1228
+
old_value: Optional[str],
"""Send configuration change notification if enabled."""
if not self.config_change_notifications or self.debug_user:
···
old_display = old_value if old_value else "(not set)"
1002
-
notification_msg = f"⚙️ **{changer}** changed {setting}: `{old_display}` → `{new_value}`"
1241
+
notification_msg = (
1242
+
f"⚙️ **{changer}** changed {setting}: `{old_display}` → `{new_value}`"
1004
-
bot_handler.send_message({
1006
-
"to": self.stream_name,
1007
-
"subject": self.topic_name,
1008
-
"content": notification_msg
1245
+
bot_handler.send_message(
1248
+
"to": self.stream_name,
1249
+
"subject": self.topic_name,
1250
+
"content": notification_msg,
self.logger.error(f"Failed to send config change notification: {e}")
handler_class = ThicketBotHandler