Image

(마지막 변경: 19.09.2024)

WikiPedia Python 봇의 기능을 테스트하기 위해 사전 구성된 텔레그램 봇 서버. 이 봇은 WikiPedia 데이터베이스에 포함된 쿼리에 응답하고 응답으로 정보를 보낼 수 있습니다.


설치를 진행해 보겠습니다:

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

데모 봇을 기존 로봇으로 교체해 보겠습니다:

/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)

완료되었습니다. 스크립트에 키 토큰을 지정하고 서비스를 다시 시작하는 것을 잊지 마세요:

service my-tel-bot restart



No Comments Yet