Python - Python TelegramBot error de artibuto.

 
Vista:
sin imagen de perfil
Val: 9
Ha disminuido su posición en 7 puestos en Python (en relación al último mes)
Gráfica de Python

Python TelegramBot error de artibuto.

Publicado por Mohamed (5 intervenciones) el 28/05/2020 22:46:22
Hola!
Tengo hecho un bot para telegram el cual hace x cosas, como sumar, dividr, darte info para los comandos, imagenes randoms de perros,etc... La cuestion es que tuve que cambiar varias lineas para poder meter la parte de generar imágenes para que luego el bot te las muestre

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import logging
import requests
import re
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler
 
#Habilito el login
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
 
logger = logging.getLogger(__name__)
 
#Al hacer click en iniciar saludamos al usuario
def iniciar(update, bot):
    """Aqui le mandamos el mensaje"""
    bot.message.reply_text('''Hola soy un bot creado por Moha de M03 1 de DAW.
Escribe /ayuda para que veas lo que puedo hacer :D, espero ayudarte. XDXD''')
 
def ayudar(update, bot):
    """Aqui digo lo que sabe hacer mi bot"""
    bot.message.reply_text('''Informacion
    /sumar X Y "Aqui el bot le suma y le da el resultado.
    /dividir X Y "Aqui el bot le divide y le da el resultado.
    /porcentaje X Y "Aqui el bot le da el porcentaje de un valor X.
    /ayudaporcentaje "Mas informacion para el uso de porcentaje."
    /perro "Te muestra una imagen aletoria de un perro."''')
 
def sumar(context, update, bot):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
 
        suma = numero1 + numero2
        bot.message.reply_text('La suma es '+str(suma))
 
    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')
 
def dividir(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
 
        div= numero1 / numero2
        update.message.reply_text('La division da '+str(div))
 
    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')
 
 
def texto(update, bot):
    bot.message.reply_text("Escriba /ayuda para ver mas informacion.")
 
def porcentaje (update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
        resultado= numero1*numero2/100
        update.message.reply_text("El "+str(context.args[1])+'% de '+str(context.args[0])+' es '+str(resultado))
    except (IndexError, ValueError):
        update.message.reply_text('Por favor, escriba correctamente los valores para poder calcular el porcentaje si necesit ayuda haga click en /ayudaporcentaje.')
 
def ayudaporcentaje (update, bot):
    bot.message.reply_text('''
    Necesita un valor X y un valor I, el valor
    X seria el valor completo y la I el porcentaje que quiere usted saber.
    Ejemplo: quiero saber el 10% de 100
    /porcentaje 100 10 (importante el orden primero el valor y luego el porcentaje.)
    el bot le respondera con 10 como resultado de porcentaje.''')
 
def get_url():
    contents = requests.get('https://random.dog/woof.json').json()
    url = contents['url']
    return url
 
def get_image_url():
    allowed_extension = ['jpg','jpeg','png']
    file_extension = ''
    while file_extension not in allowed_extension:
        url = get_url()
        file_extension = re.search("([^.]*)$",url).group(1).lower()
    return url
 
def perro(bot, update):
    url = get_image_url()
    chat_id = update.message.chat_id
    bot.send_photo(chat_id=chat_id, photo=url)
 
def main():
    """Aqui iniciamos el bot y lo que hacemos es crear un token para poder iniciar el bot en telegram"""
    session = Updater("TOKEN xxxxxxxx")
    # el token lo guardamos en un a variable llamada botm3
    botm3 = session.dispatcher
 
 
    botm3.add_handler(CommandHandler("Iniciar", iniciar))
    botm3.add_handler(CommandHandler("Ayuda", ayudar))
    botm3.add_handler(CommandHandler("Sumar", sumar))
    botm3.add_handler(CommandHandler("Dividir", dividir))
    botm3.add_handler(CommandHandler("Dividir", dividir))
    botm3.add_handler(CommandHandler("ayudaporcentaje", ayudaporcentaje))
    botm3.add_handler(CommandHandler("porcentaje", porcentaje))
    botm3.add_handler(CommandHandler("perro", perro))
    botm3.add_handler(MessageHandler(Filters.text, texto))
    session.start_polling()
 
    #Aqui empieza el bot
    #sesion.start_polling()
 
    #Aqui decimos que es un bulce y que no pare hasta que le demos a ctrl+c
    session.idle()
if __name__ == '__main__':
    main()

Me muestra el seguiente error el cual me hace petar el bot y asi deje de funcionar, el mensaje del fallo es el seguiente:

1
builtins.TypeError: sumar() missing 1 required positional argument: 'bot'

ya he probado lo siguiente en el código y nada a ver si alguien tiene la solución:

1
2
3
4
5
6
7
8
9
10
def sumar(context, update):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
 
        suma = numero1 + numero2
        update.message.reply_text('La suma es '+str(suma))
 
    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

También he probado esto:

def sumar(context, update, bot):
1
2
3
4
5
6
7
8
9
try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
 
        suma = numero1 + numero2
        bot.message.reply_text('La suma es '+str(suma))
 
    except (IndexError, ValueError):
        bot.message.reply_text('Por favor utiliza dos numeros')

Tambien he hecho lo siguente pero me da error de atributos:

1
2
3
4
5
6
7
8
9
10
def sumar(context, bot):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
 
        suma = numero1 + numero2
        bot.message.reply_text('La suma es '+str(suma))
 
    except (IndexError, ValueError):
        bot.message.reply_text('Por favor utiliza dos numeros')

Y tambien he intentado esto:
1
2
3
4
5
6
7
8
9
10
def sumar(update, context):
    try:
        numero1 = int(context.args[0])
        numero2 = int(context.args[1])
 
        suma = numero1 + numero2
        update.message.reply_text('La suma es '+str(suma))
 
    except (IndexError, ValueError):
        update.message.reply_text('Por favor utiliza dos numeros')

En el ultimo me salta este este error:
1
builtins.AttributeError: 'Update' object has no attribute 'args'

Alguien sabe alguna solución seria de mucha ayuda.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder