python-telegram-bot for (v20.x) TypeError: bad operand type for unary ~: 'type' - python-telegram-bot

I am trying to build a telegram bot, I have just reproduce the code:
from telegram.ext import MessageHandler
from telegram.ext import filters
from telegram.ext import Application
from telegram import Update
from telegram.ext import ContextTypes
from decouple import config
def testFunc (update: Update, context: ContextTypes.DEFAULT_TYPE):
print('Hi')
def main():
BOT_TOKEN = config('TELE_BOT_API_KEY_2')
application = Application.builder().token(BOT_TOKEN).build()
application.add_handler(MessageHandler(filters.Text & ~filters.Command, testFunc))
application.run_polling()
if __name__ == '__main__':
main()
The error this code shows is:
Bot\AsyncAdvanceBot\test3.py", line 16, in main
application.add_handler(MessageHandler(filters.Text & ~filters.Command, testFunc))
TypeError: bad operand type for unary ~: 'type'
I am using python-telegram-bot api v20.x
I know this might be a naive problem that I might be missing.
Thanks!
I tried changing the code to different format but it doesn't work.

I got it! It was as I said naive error. I was not thinking straight😅
I have seen the document even earlier and was only focusing on making filters.Command to filters.COMMAND, but forgot to change filters.Text to filters.TEXT.
just replaced
filters.Text & ~filters.Command
with
filters.TEXT & ~filters.COMMAND

Related

Error when importing sklearn in pipeline component

When I run this simple pipeline (in GCP's Vertex AI Workbench) I get an error:
ModuleNotFoundError: No module named 'sklearn'
Here is my code:
from kfp.v2 import compiler
from kfp.v2.dsl import pipeline, component
from google.cloud import aiplatform
#component(
packages_to_install=["sklearn"],
base_image="python:3.9",
)
def test_sklearn():
import sklearn
#pipeline(
pipeline_root=PIPELINE_ROOT,
name="sklearn-pipeline",
)
def pipeline():
test_sklearn()
compiler.Compiler().compile(pipeline_func=pipeline, package_path="sklearn_pipeline.json")
job = aiplatform.PipelineJob(
display_name=PIPELINE_DISPLAY_NAME,
template_path="sklearn_pipeline.json",
pipeline_root=PIPELINE_ROOT,
location=REGION
)
job.run(service_account=SERVICE_ACCOUNT)
What do I do wrong? :)
It seems that the package name sklearn does not work after a version upgrade.You need to change the value of packages_to_install from "sklearn" to "scikit-learn" in the #component block.

Discord Slash Command options not working

I am trying to make a slash command in discord.
import discord
import datetime
import pickle
import os
from discord.ext import commands
from dislash import *
bot = commands.Bot(command_prefix="-")
inter_client = InteractionClient(bot, test_guilds=[345328981039382528])
#bot.event
async def on_ready():
print("Nick ist online!")
#inter_client.slash_command(
name="kick", # Defaults to the function name
description="kick a user",
guild_ids=[345328981039382528],
options=[
create_option(
name="user",
description="Choose a user",
option_type=6,
required=True
)
]
)
async def kick(inter, user:str):
pass
bot.run("-")
If i am trying to run it it says:
Traceback (most recent call last):
line 20, in <module>
create_option(
NameError: name 'create_option' is not defined
So someone said i should add the following line:
from discord_slash.utils.manage_commands import create_option
But this does not help. After adding this it says:
line 7, in <module>
from discord_slash.utils.manage_commands import create_option
ModulNotFoundError: No module named 'discord_slash'
However if i go to cmd and do:
pip install discord-py-slash-command
It says its already installed.
Does anyone know what i am doing wrong? Thanks for helping
options=[
Option("user","Choose a user", OptionType.USER)
]
Try changing your options in the slash command to as follows.

Streamlit Unhashable TypeError when i use st.cache

when i use the st.cache decorator to cash hugging-face transformer model i get
Unhashable TypeError
this is the code
from transformers import pipeline
import streamlit as st
from io import StringIO
#st.cache(hash_funcs={StringIO: StringIO.getvalue})
def model() :
return pipeline("sentiment-analysis", model='akhooli/xlm-r-large-arabic-sent')
after searching in issues section in streamlit repo
i found that hashing argument is not required , just need to pass this argument
allow_output_mutation = True
This worked for me:
from transformers import pipeline
import tokenizers
import streamlit as st
import copy
#st.cache(hash_funcs={tokenizers.Tokenizer: lambda _: None, tokenizers.AddedToken: lambda _: None})
def get_model() :
return pipeline("sentiment-analysis", model='akhooli/xlm-r-large-arabic-sent')
input = st.text_input('Text')
bt = st.button("Get Sentiment Analysis")
if bt and input:
model = copy.deepcopy(get_model())
st.write(model(input))
Note 1:
calling the pipeline with input model(input) changes the model and we shouldn't change a cached value so we need to copy the model and run it on the copy.
Note 2:
First run will load the model using the get_model function next run will use the chace.
Note 3:
You can read more about Advanced caching in stremlit in thier documentation.
Output examples:

Why is the output file from Biopython not found?

I work with a Mac. I have been trying to make a multiple sequence alignment in Python using Muscle. This is the code I have been running:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="testunaligned.fasta", out="testunaligned.aln", clwstrict=True)
print(cline)
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)
I keep getting the following error:
FileNotFoundError: [Errno 2] No such file or directory: 'testunaligned.aln'
Does anyone know how I could fix this? I am very new to Python and computer science in general, and I am totally at a loss. Thanks!
cline in your code is an instance of MuscleCommandline object that you initialized with all the parameters. After the initialization, this instance can run muscle, but it will only do that if you call it. That means you have to invoke cline()
When you simply print the cline object, it will return a string that corresponds to the command you can manually run on the command line to get the same result as when you invoke cline().
And here the working code:
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(
input="testunaligned.fasta",
out="testunaligned.aln",
clwstrict=True
)
print(cline)
cline() # this is where mucle runs
from Bio import AlignIO
align = AlignIO.read(open("testunaligned.aln"), "clustal")
print(align)

shutil error: "Module 'shutil' has no 'copy' member"

I am still learning python but got stuck here:
from pathlib import Path
import os
import shutil
p = Path.home()
shutil.copy(p / 'G:\souce.txt', p / 'G:\dest.text')
The error is:
shutil: shutil
Anomalous backslash in string: '\s'. String constant might be missing an r prefix.pylint(anomalous-
backslash-in-string)
Anomalous backslash in string: '\d'. String constant might be missing an r prefix.pylint(anomalous-
backslash-in-string)
Module 'shutil' has no 'copy' memberpylint(no-member)
Not able to go for the next step. So any suggestions please.
You can just do:
import shutil
shutil.copy('G:\souce.txt', 'G:\dest.text')

Resources