Image

(Last change: 04.05.2024)

To test the functionality of the WikiPedia Python bot, we used preconfigured telegram bot server. This bot can respond to queries contained in the WikiPedia database and send information in response.

Let's proceed with the installation:

source my-tel-bot/bin/activate
pip3 install wikipedia

Let's replace our demo bot with the existing one:

/root/my-tel-bot/bot.py

import telebot, wikipedia, re

# Create an instance of the bot
bot = telebot.TeleBot('Key received from @BotFather')

# Install Russian language in Wikipedia
wikipedia.set_lang("ru")

# We clean the text of the article in Wikipedia and limit it to a thousand characters
def getwiki(s):
try:
ny = wikipedia.page(s)

# Getting the first thousand characters
wikitext=ny.content[:1000]

# Split by dot
wikimas=wikitext.split('.')

# Discarding everything after the last dot
wikimas = wikimas[:-1]

# Create an empty variable for text
wikitext2 = ''

# We go through the lines where there are no equal signs (that is, everything except the headings)
for x in wikimas:
if not('==' in x):

# If there are more than three characters left in the string, we add it to our variable and return the dots lost when splitting the strings into place
if(len((x.strip()))>3):
wikitext2=wikitext2+x+'.'
else:
break

# Now, with the help of regular expressions, we remove the markup
wikitext2=re.sub('\([^()]*\)', '', wikitext2)
wikitext2=re.sub('\([^()]*\)', '', wikitext2)
wikitext2=re.sub('\{[^\{\}]*\}', '', wikitext2)

# Returning a text string
return wikitext2

# Handling the exception that the wikipedia module might have returned when requested
except Exception as e:
return 'The encyclopedia has no information about it.'

# The function that processes the command /start
@bot.message_handler(commands=["start"])
def start(m, res=False):
bot.send_message(m.chat.id, 'Send me any word and I will look it up on Wikipedia')

# Receiving messages from a user
@bot.message_handler(content_types=["text"])
def handle_text(message):
bot.send_message(message.chat.id, getwiki(message.text))

# Launching the bot
bot.polling(none_stop=True, interval=0)

Done, don't forget to specify your key token in the script and restart the service:

service my-tel-bot restart



No Comments Yet