I'm using this line for a custom keyboard on my Telegram bot:
markup = ReplyKeyboardMarkup(keyboard=[['Time', KeyboardButton(text='NewKey')],["File", "Audio"]])
I want my bot to change custom keyboard to another when user sends NewKey. And it will send show up a new custom keyboard but it's layout will be same as the default keyboard.
I have tried this but it is not working:
elif command == 'NewKey':
markup = ReplyKeyboardMarkup(keyboard=[['More', KeyboardButton(text='More2')],["More3", "More5"]])
Here is my full code of my bot:
import time, datetime
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton
now = datetime.datetime.now()
def action(msg):
chat_id = msg['`chat']['id']
command = msg['text']
print('Received: %s' % command)
markup = ReplyKeyboardMarkup(keyboard=[['Time', KeyboardButton(text='NewKey')],["File", "Audio"]])
if command == '/start':
telegram_bot.sendMessage (chat_id, str("Hi! Which one do you want? choose from the below keyboard buttons."), reply_markup=markup)
telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute))
elif command == 'NewKey':
markup = ReplyKeyboardMarkup(keyboard=[['More', KeyboardButton(text='More2')],["More3", "More5"]]))
elif command == 'Time':
telegram_bot.sendMessage(chat_id, str(now.hour)+str(":")+str(now.minute))
elif command == '/file':
telegram_bot.sendDocument(chat_id, document=open('/home/pi/Aisha.py'))
elif command == '/audio':
telegram_bot.sendAudio(chat_id, audio=open('/home/pi/test.mp3'))
telegram_bot = telepot.Bot('MY-BOT-TOKEN')
print((telegram_bot.getMe()))
MessageLoop(telegram_bot, action).run_as_thread()
print('Up and Running....')
while 1:
time.sleep(10)
`
Related
I am also using flask and I am trying to run the code from github.
Error :
(env) PS E:\VIDEOBOT> & e:/VIDEOBOT/env/Scripts/python.exe e:/VIDEOBOT/reddit/subreddit.py
Traceback (most recent call last):
File "e:\VIDEOBOT\reddit\subreddit.py", line 1, in
from utils.console import print_markdown, print_step, print_substep
ModuleNotFoundError: No module named 'utils'
Below is the code.
subreddit.py
from utils.console import print_markdown, print_step, print_substep
import praw
import random
from dotenv import load_dotenv
import os
def get_subreddit_threads():
"""
Returns a list of threads from the AskReddit subreddit.
"""
load_dotenv()
print_step("Getting AskReddit threads...")
if os.getenv("REDDIT_2FA").lower() == "yes":
print("\nEnter your two-factor authentication code from your authenticator app.\n")
code = input("> ")
print()
pw = os.getenv("REDDIT_PASSWORD")
passkey = f"{pw}:{code}"
else:
passkey = os.getenv("REDDIT_PASSWORD")
content = {}
reddit = praw.Reddit(
client_id=os.getenv("REDDIT_CLIENT_ID"),
client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
user_agent="Accessing AskReddit threads",
username=os.getenv("REDDIT_USERNAME"),
password=passkey,
)
if os.getenv("SUBREDDIT"):
subreddit = reddit.subreddit(os.getenv("SUBREDDIT"))
else:
# ! Prompt the user to enter a subreddit
try:
subreddit = reddit.subreddit(
input("What subreddit would you like to pull from? ")
)
except ValueError:
subreddit = reddit.subreddit("askreddit")
print_substep("Subreddit not defined. Using AskReddit.")
threads = subreddit.hot(limit=25)
submission = list(threads)[random.randrange(0, 25)]
print_substep(f"Video will be: {submission.title} :thumbsup:")
try:
content["thread_url"] = submission.url
content["thread_title"] = submission.title
content["comments"] = []
for top_level_comment in submission.comments:
content["comments"].append(
{
"comment_body": top_level_comment.body,
"comment_url": top_level_comment.permalink,
"comment_id": top_level_comment.id,
}
)
except AttributeError as e:
pass
print_substep("Received AskReddit threads successfully.", style="bold green")
return content
console.util.py
from rich.console import Console
from rich.markdown import Markdown
from rich.padding import Padding
from rich.panel import Panel
from rich.text import Text
console = Console()
def print_markdown(text):
"""Prints a rich info message. Support Markdown syntax."""
md = Padding(Markdown(text), 2)
console.print(md)
def print_step(text):
"""Prints a rich info message."""
panel = Panel(Text(text, justify="left"))
console.print(panel)
def print_substep(text, style=""):
"""Prints a rich info message without the panelling."""
console.print(text, style=style)
I have got this code from redditbot version--1.0.0
Just like the title, the code works perfectly fine, without any errors at all, and when i tested certain things, modules that didn't need to be installed separately would work, but the ones that needed to be installed through the command terminal will just make the program close automatically.
Does anyone know how to fix this
i tested running the code with specific modules, with a code "input('press enter to exit.')" so i have to close the window manually. Only the modules i had to download separately would make the program close automatically.
this is my code
import speech_recognition as sr
import subprocess as rr
from playsound import playsound
from pynput.keyboard import Key, Controller
import time
import webbrowser
import os
import random
import operator
import psutil
response = random.randint(1,2)
if response==1:
re = 'Acheive.mp3'
elif response==2:
re = 'At-Your-Service.mp3'
def close_app(app_name):
running_apps=psutil.process_iter(['pid','name']) #returns names of running processes
found=False
for app in running_apps:
sys_app=app.info.get('name').split('.')[0].lower()
if sys_app in app_name.split() or app_name in sys_app:
pid=app.info.get('pid') #returns PID of the given app if found running
try: #deleting the app if asked app is running.(It raises error for some windows apps)
app_pid = psutil.Process(pid)
app_pid.terminate()
found=True
except: pass
else: pass
if not found:
print(app_name+" not found running")
else:
print(app_name+'('+sys_app+')'+' closed')
def takeCommand():
r = sr.Recognizer()
playsound(re)
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
query = r.recognize_google(audio, language ='en-in')
print(f"User said: {query}\n")
except Exception as e:
print(e)
print("Unable to Recognize your voice.")
return "None"
return query
query = takeCommand().lower()
if 'game on' in query or 'steam' in query:
playsound('Jarvis-Game.mp3')
rr.Popen("C:\Program Files (x86)\Steam\steam.exe")
elif "let's chat" in query or "discord" in query:
keyboard = Controller()
keyboard.press(Key.ctrl)
keyboard.press(Key.alt)
keyboard.press('q')
keyboard.release(Key.ctrl)
keyboard.release(Key.alt)
keyboard.release('q')
elif "tunes" in query or 'spotify' in query:
keyboard = Controller()
keyboard.press(Key.ctrl)
keyboard.press(Key.alt)
keyboard.press('s')
keyboard.release(Key.ctrl)
keyboard.release(Key.alt)
keyboard.release('s')
time.sleep(5)
keyboard.press(Key.space)
keyboard.release(Key.space)
elif "watch something" in query or 'youtube' in query:
webbrowser.open("https://www.youtube.com/")
elif "introduce" in query or 'who are you' in query:
playsound('Jarvis-Intro.mp3')
elif 'model' in query or 'untiy' in query:
keyboard = Controller()
keyboard.press(Key.ctrl)
keyboard.press(Key.alt)
keyboard.press('u')
keyboard.release(Key.ctrl)
keyboard.release(Key.alt)
keyboard.release('u')
playsound('Project.mp3')
elif 'shutdown' in query or 'security protocol' in query:
playsound('Shutting-Down.mp3')
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
elif 'uploaded' in query:
playsound('Uploaded.mp3')
elif 'music' in query:
query = takeCommand().lower()
if 'cyberdream' in query:
webbrowser.open('https://www.youtube.com/watch?v=yhCuCqJbOVE')
elif 'jazz' in query:
webbrowser.open('https://www.youtube.com/watch?v=idlUMwT4w84&t=2993s')
elif 'upbeat' in query:
webbrowser.open('https://www.youtube.com/watch?v=uoSTi_HZj5o&list=RDuoSTi_HZj5o&start_radio=1')
elif 'google' in query:
query = takeCommand().lower()
webbrowser.open('https://www.google.com/search?q='+query)
elif 'solve' in query:
response = random.randint(1,2)
if response==1:
re = 'Acheive.mp3'
elif response==2:
re = 'At-Your-Service.mp3'
playsound(re)
r = sr.Recognizer()
my_mic_device = sr.Microphone(device_index=1)
with my_mic_device as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
my_string=r.recognize_google(audio)
print(my_string)
def get_operator_fn(op):
return {
'+' : operator.add,
'-' : operator.sub,
'x' : operator.mul,
'*' : operator.mul,
'/' : operator.__truediv__,
'divided' :operator.__truediv__,
'Mod' : operator.mod,
'mod' : operator.mod,
'^' : operator.xor,
}[op]
def eval_binary_expr(op1, oper, op2):
op1,op2 = int(op1), int(op2)
return get_operator_fn(oper)(op1, op2)
print(eval_binary_expr(*(my_string.split())))
time.sleep(5)
elif 'close' in query and 'app' in query:
query = takeCommand().lower()
close_app(query)
elif 'skip' in query and 'video' in query:
time.sleep(3)
keyboard = Controller()
keyboard.press(Key.shift)
keyboard.press('n')
keyboard.release(Key.shift)
keyboard.release('n')
before i reset my computer to fix the microphone, it was working perfectly fine and had no troubles.
Hello I recently made a help command using discord_components buttons (I know they arent fully supported by Discord.py) but I still went ahead. The problem is that whenever I run the command and receive the Buttons to click on, they alway say "This Interaction Failed". I can't seem to find what's wrong. Please help.
Thanking You,
NightMX.
import discord
from discord.ext import commands
from discord_components.component import ButtonStyle
from discord_components import DiscordComponents, Button, Select, SelectOption
from discord_components.interaction import InteractionType
class BotCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpv2(self, ctx):
funbutton = Button(style=ButtonStyle.grey, label="Fun Commands", id="funcmds")
monkedevbutton = Button(style=ButtonStyle.grey, label="Attachment Commands", id="monkecmds")
# utilitybutton = Button(style = ButtonStyle.grey, label = "3", id = "embed3")
funembed = discord.Embed(title="Fun Commands", colour=discord.Colour.orange())
funembed.add_field(name="k.joke", value="Sends a Random joke from PyJokes")
monkedevembed = discord.Embed(title="Fun Commands", colour=discord.Colour.blurple())
monkedevembed.add_field(name="k.dog", value="Sends a Random Dog Fact")
monkedevembed.add_field(name="k.monkey", value="Sends a Monkey's Picture")
monkedevembed.add_field(name="k.bird", value="Sends a Bird's Picture")
await ctx.send(
"Kola's Beta Help Command!",
components=[[funbutton, monkedevbutton]]
)
buttons = {
"funcmds": funembed,
"monkedcmds": monkedevembed
}
while True:
event = await self.bot.wait_for('button_click')
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
if response is None:
await event.channel.send(
"Something went Wrong"
)
if event.channel == ctx.channel:
await event.respond(
type=InteractionType.ChannelMessageWithSource, embed=response
)
def setup(client):
client.add_cog(BotCommands(client))
should be content="something" instead of embed = response
i'm actually trying to dev a slack bot with python. I'm learning python and slack api at the same time and i want to know how can i use a value printed before ?
import os
from slackeventsapi import SlackEventAdapter
from slack import WebClient
from slack.errors import SlackApiError
import time
client = WebClient(token=os.environ['SLACK_KEY'])
response = client.chat_postMessage(
channel='starterbot',
text="Hello, are you there ?")
assert response["message"]["text"] == "Hello, are you there ?"
RTM_READ_DELAY = 2
time.sleep(RTM_READ_DELAY)
print(response['ts'])
# if response == "Yes":
# elif response != "Yes":
# client.chat_postMessage(
# channel='starterbot',
# text="Bye!")
if client.conversations_replies(channel='C01665VJ2JH', ts='1593523175.013300') == "Yes":
client.chat_postMessage(channel='starterbot', text="u sure ?")
i want to create a variable to save the ts value that i print, and then use it in the client.conversations_replies.
Ty for your help
I wrote the program below,
can = CAN("can0", bitrate=50000, listen_only=True, error_reporting=True)
while True:
msg = can.recv()
print "Msg: ", msg
But it only displays the standard S or Extended X flags even though when I run the command in Terminal to check the network activity, I can see that the error counter is increasing.
import can
import CAN
import time
import logging
#logging.basicConfig(level=logging.DEBUG)
print("Initializing Listener")
can1 = CAN('can0', bitrate=500000, listen_only=True, err_reporting=True)
#print "Bus is : ", can1.bus.get_can_bus()
can1.bus.set_filters(can_filters=[{"can_mask":0x7FF, "can_id":0x00000000, "extended":False}])
CAN_ERR_FLAG = 0x20000000
while 1:
msg = can1.recv()
if (msg.arbitration_id & CAN_ERR_FLAG) == CAN_ERR_FLAG:
print "Can Error Caught"
elif msg.is_error_frame:
print "Finally Error Frame"
How can I read the error-frames of the CAN-bus ?
Things work fine when I use commnad candump -e any,0:0,#FFFFFFFF
Use Python - 3
import binascii
channel_name = "vcan0"
socketID = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
# socketID.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_ERR_FILTER, 0x1FFFFFFF)
error = socketID.bind((channel_name,))
print(binascii.hexlify(socketID.recv(32)))