research-hunter / telegram_bot.py
ballagb19's picture
Upload telegram_bot.py with huggingface_hub
15fcf1c verified
"""
Research Hunter Telegram Bot
============================
Bot username: @SearchingWild_Bot
Token: 8774937259:AAGRWGYTtKRYzLVb3EHw-4iRqpDXdsTMH-o
Commands:
- /start - Welcome message
- /search <query> - Search for papers
- /help - Show help
Usage:
- Send a research topic to search
- Get results with citations
"""
import os
import sys
sys.stdout.reconfigure(encoding='utf-8')
import json
import logging
from datetime import datetime
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, JobQueue
# Import the search engine
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import ultimate_super_engine as engine
# Bot configuration
BOT_TOKEN = "8774937259:AAGRWGYTtKRYzLVb3EHw-4iRqpDXdsTMH-o"
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Command handlers
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a message when the command /start is issued."""
welcome = """
πŸ”¬ *Research Hunter Bot*
Welcome to Research Hunter! I can search across 117+ academic platforms for research papers.
Commands:
/search \<query\> - Search for papers
/help - Show help
/start - Welcome message
Just send me a research topic and I'll find papers for you!
"""
await update.message.reply_text(welcome, parse_mode='Markdown')
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a message when the command /help is issued."""
help_text = """
πŸ“š *Research Hunter Help*
Search for academic papers across 117+ platforms including:
- Semantic Scholar, OpenAlex, arXiv, PubMed
- CrossRef, CORE, Europe PMC
- HAL, Zenodo, OATD, DOAB
- Major publishers: MDPI, PLoS, Springer, Wiley, IEEE
- And many more...
Each search returns up to 250 papers per platform with:
- Title, Authors, Year
- Journal, DOI, Citations
- Source platform
Commands:
/start - Start the bot
/help - Show this help
/search \<topic\> - Search for papers
"""
await update.message.reply_text(help_text, parse_mode='Markdown')
async def search_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle the /search command."""
query = ' '.join(context.args)
if not query:
await update.message.reply_text("Please provide a search query.\nUsage: /search machine learning")
return
await update.message.reply_text(f"πŸ” Searching for: *{query}*", parse_mode='Markdown')
try:
# Search across all platforms
results, stats = engine.search_all_platforms(query, limit_per_platform=50)
# Format response
response = f"""
πŸ“Š *Search Results for: {query}*
βœ… *Total Papers Found:* {stats['total_papers']}
πŸ“ˆ *Total Citations:* {stats['total_citations']}
🌐 *Platforms Searched:* {stats['platforms_searched']}
πŸ“š *Top 10 Papers:*
"""
# Add top papers
for i, paper in enumerate(results[:10], 1):
title = paper.get('title', '')[:60]
authors = ', '.join(paper.get('authors', [])[:2])
year = paper.get('year', 'N/A')
citations = paper.get('citations', 0)
source = paper.get('source', '')
response += f"""
{i}. *{title}...*
πŸ‘₯ {authors}
πŸ“… {year} | ⭐ {citations} citations | πŸ“ {source}
"""
# Add platform breakdown
response += """
πŸ“Š *Platform Results:*
"""
working = [(k, v) for k, v in stats['platform_stats'].items() if v > 0]
for name, count in sorted(working, key=lambda x: -x[1])[:15]:
response += f" β€’ {name}: {count}\n"
await update.message.reply_text(response, parse_mode='Markdown')
except Exception as e:
logger.error(f"Search error: {e}")
await update.message.reply_text(f"❌ Error: {str(e)[:200]}")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle regular messages as search queries."""
query = update.message.text
if query.startswith('/'):
return # Skip commands
await update.message.reply_text(f"πŸ” Searching for: *{query}*", parse_mode='Markdown')
try:
results, stats = engine.search_all_platforms(query, limit_per_platform=30)
response = f"""
πŸ“Š *Results for: {query}*
βœ… *Papers:* {stats['total_papers']} | ⭐ *Citations:* {stats['total_citations']}
πŸ“š *Top 5:*
"""
for i, paper in enumerate(results[:5], 1):
title = paper.get('title', '')[:50]
citations = paper.get('citations', 0)
response += f"{i}. {title}... ({citations} citations)\n"
if len(results) > 5:
response += f"\n...and {len(results) - 5} more papers!"
await update.message.reply_text(response, parse_mode='Markdown')
except Exception as e:
logger.error(f"Error: {e}")
await update.message.reply_text(f"❌ Error: {str(e)[:100]}")
async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Log errors caused by updates."""
logger.error(f'Update "{update}" caused error "{context.error}"')
def main():
"""Start the bot."""
# Create the Application and pass your bot's token.
application = Application.builder().token(BOT_TOKEN).build()
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("search", search_command))
# on noncommand i.e. message - search as message
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
# log all errors
application.add_error_handler(error_handler)
# Run the bot
print("πŸ€– Research Hunter Bot starting...")
print("Bot: @SearchingWild_Bot")
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == '__main__':
main()