M
M
Maxim Samonov2022-02-23 23:17:43
Python
Maxim Samonov, 2022-02-23 23:17:43

How to add a parser to a discord bot?

I wanted to make my own discord bot, and I already added one function that gives out roles when responding to a message, but I want to add another function that, on command from a person, would give discounts on some games in the incentive. Here is actually my code, the main problem is that it does not produce anything at the command.

import discord
from discord import utils
from bs4 import BeautifulSoup
import requests
import rolescfgcom as config
#ВОТ САМ ПАРСЕР
url = 'https://store.steampowered.com/specials/?l=russian#p=0&tab=TopSellers'

response = requests.get(url=url).text

#with open('index.html', 'w', encoding='utf-8') as file:
    #file.write(response)

soup = BeautifulSoup(response, 'lxml')

all_games = soup.find_all('a', class_='tab_item')

result_list = []

for item in all_games:
    name = item.find(class_='tab_item_name').text.strip()
    price_final = item.find(class_='discount_final_price').text.strip()
    try:
        sale = item.find('div', class_='discount_pct').text.strip()
    except:
        sale = 'отсутствует'

    result_list.append({
        'name': name,
        'price': price_final,
        'sale': sale
    })
    
#for item in result_list:
    #n = print(item['name'])
    #p = print(item['price'])
    #s = print(item['sale'])
    #hz = print('-------------------')

intents = discord.Intents.all()
intents.members = True
 
client = discord.Client()

class MyClient(discord.Client):
    async def on_ready():
         print('We have logged in as {0.user}'.format(client))
 
    async def on_raw_reaction_add(self, payload):
        if payload.message_id == config.POST_ID:
            channel = self.get_channel(payload.channel_id) # получаем объект канала
            message = await channel.fetch_message(payload.message_id) # получаем объект сообщения
            member = utils.get(message.guild.members, id=payload.user_id) # получаем объект пользователя который поставил реакцию
 
            try:
                emoji = str(payload.emoji) # эмоджик который выбрал юзер
                role = utils.get(message.guild.roles, id=config.ROLES[emoji]) # объект выбранной роли (если есть)
            
                if(len([i for i in member.roles if i.id not in config.EXCROLES]) <= config.MAX_ROLES_PER_USER):
                    await member.add_roles(role)
                    print('[SUCCESS] User {0.display_name} has been granted with role {1.name}'.format(member, role))
                else:
                    await message.remove_reaction(payload.emoji, member)
                    print('[ERROR] Too many roles for user {0.display_name}'.format(member))
            
            except KeyError as e:
                print('[ERROR] KeyError, no role found for ' + emoji)
            except Exception as e:
                print(repr(e))
 
    async def on_raw_reaction_remove(self, payload):
        channel = self.get_channel(payload.channel_id) # получаем объект канала
        message = await channel.fetch_message(payload.message_id) # получаем объект сообщения
        member = utils.get(message.guild.members, id=payload.user_id) # получаем объект пользователя который поставил реакцию
 
        try:
            emoji = str(payload.emoji) # эмоджик который выбрал юзер
            role = utils.get(message.guild.roles, id=config.ROLES[emoji]) # объект выбранной роли (если есть)
 
            await member.remove_roles(role)
            print('[SUCCESS] Role {1.name} has been remove for user {0.display_name}'.format(member, role))
 
        except KeyError as e:
            print('[ERROR] KeyError, no role found for ' + emoji)
        except Exception as e:
            print(repr(e))
  
    async def on_message(message):
        if message.author == client.user:
            return
    # А ВОТ САМА ФУНКЦИЯ С ПОМОЩЬЮ КОТОРОЙ БОТ БЫ ВЫДАВАЛ БЫ СКИДКИ
        if message.content.startswith('СКИДКУ!'):
            await message.channel.send(for item in result_list:
                                           n = print(item['name'])
                                           p = print(item['price'])
                                           s = print(item['sale'])
                                           hz = print('-------------------')
                                                                    

client = discord.Client(intents=intents)
 
# RUN
client = MyClient(intents = discord.Intents.all())
client.run(config.TOKEN)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2022-02-24
@Maks_432

n = print(item['name'])
First, it doesn't output anything to where ?
Second, print() prints to standard output, usually the console. Do not send anything to the discord through it.
Third, print() always returns None. So n will always be None, and the assignment doesn't make sense.
Fourth, why not use the normal command handler from discord.ext.commands.Bot? It also allows you to respond to messages, in addition to other benefits specifically for the bot. This is provided that you want exactly the reaction to the message and do not agree to do with the usual command.
Fifth, if you're not sure what print() is, why are you trying to write bots?
Well, about the little things, like "the bot parses games only at startup, and does not update the information in the future," I'm not saying...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question