首页 > 解决方案 > Django 查询 - 将用户类与 Telegram Bot 的 OnetoOnefield 类连接

问题描述

我在从与用户类连接的自定义类中查询属性时遇到问题。

我的目标:我想通过电报机器人每次鼠标点击在我的网站上向我的手机发送消息(消息传递有效) - 为此我需要用户的聊天 ID

由于有多个用户,我将 chat_id 存储在我创建的新模型中,该模型通过 onetoonefield 链接到 User 模型:

User = get_user_model()

class TelegramProfile(models.Model):
    name = models.CharField(default="",max_length=200,blank=True,unique=True)
    user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="user_id")
    telegram_chat_id = models.CharField(max_length=40,default="",editable=True,blank=True,unique=True)
   
    def __str__(self):
        return str(self.name)

我的用户模型是内置模型:

class User(auth.models.User, auth.models.PermissionsMixin):

def __str__(self):
    return f"@{self.username}"

因此,在我的 views.py 文件中,我具有获取消息的函数(另一个名为 Recipe 的模型类 - 我通过主键识别它)和属于特定用户的 chat_id:

  def bot(request,msg,chat_id,token=my_token):
        bot=telegram.Bot(token=token)
        bot.send_message(chat_id=chat_id, text=msg)



  def home(request,pk):
      recipe = get_object_or_404(Recipe,pk=pk)
      user = request.user
      chat_id = User.objects.get(TelegramProfile.telegram_chat_id,user) #with this query I try to grab the chat_id of the logged in user
      ingredients = recipe.ingredients
      ingredients = ingredients.split("<p>")
      ingredients = "\n".join(ingredients)
      ingredients = strip_tags(ingredients)
      bot(request,ingredients,chat_id)
      return render(request,"recipes/send_recipe.html")

所以我的问题是:

-如何查询chat_id,以便:将调用特定登录用户的chat_id,以便我可以将其插入机器人函数以将消息发送到该特定ID?

我还是 django 的新手,所以我还在学习查询,提前非常感谢!!!

标签: pythondjangoviewmodeltelegram

解决方案


编辑:能够自己解决:

def send_recipe(request, pk):
  try:
    if request.method == "POST":
        data_option = str(request.POST[
                              "testselect"])  # testselect is the select form in recipe_detail.html with which I select 1 of the 2 options
        if data_option == "Ingredients":
            recipe = get_object_or_404(Recipe, pk=pk)
            recipe_name = recipe.name.upper()
            ingredients = recipe.ingredients
            ingredients = ingredients.split("<p>")
            ingredients = "\n".join(ingredients)
            ingredients = strip_tags(ingredients)
            message = f"{recipe_name}: \n {ingredients}"

            user = TelegramProfile.objects.get(
                user=request.user)  # use get instead of filter! filter returns the name but can t use it as object, with get I get the object and I can use the attributes on it!
            chat_id = user.telegram_chat_id
            bot(request, message, chat_id)
            return render(request, "recipes/send_recipe.html")
        elif data_option == "Ingredients & Description":
            recipe = get_object_or_404(Recipe, pk=pk)
            recipe_name = recipe.name.upper()  # recipe name
            ingredients = recipe.ingredients
            ingredients = ingredients.split("<p>")
            ingredients = "\n".join(ingredients)
            ingredients = strip_tags(
                ingredients)  # we grab recipes ingredients and mute them, split at p tag, then add a new line and join them then remove tags
            recipe_description = recipe.description
            recipe_description = recipe_description.split("<p>")
            recipe_description = "\n".join(recipe_description)
            recipe_description = strip_tags(recipe_description)
            message = f"{recipe_name}: \n {ingredients} \n \n {recipe_description}"

            user = TelegramProfile.objects.get(user=request.user)
            chat_id = user.telegram_chat_id
            bot(request, message, chat_id)
            return render(request, "recipes/send_recipe.html")
    else:
        return render(request, "recipes/create_telegram.html")
  except Exception:
    return render(request, "recipes/create_telegram.html")

推荐阅读