一个vscode插件,他们帮你高效工作,而我只在乎你有没有按时吃饭

useage

Remind-me

为了防止世界被破坏,为了守护世界的和平,为了保持力量与 PM 干架,为了和我一样热爱工作而忘记吃饭的优秀程序员的身体健康,在此大家献上我刚刚造出来的沙雕vscode插件:Remind-me。 主要功能有:提醒你吃饭下班,使用和风天气API获取当前天气、下雨提醒别忘了带伞和展示未来12小时的温度曲线 。

ctrl+shift+, 一键开启沙雕生活

他们帮你高效工作,而我只在乎你有没有按时吃饭. ——— 社会王

They help you work efficiently, but I only care if you are eating on time. —— shehuiwang. google translate


Features

提醒你吃饭下班,顺便看看天气

Remind you to do something, eat or get off work, etc. Show current weather and temperature curve


Quick start:

配置项

Name | Description | Default

remind-me.defaultCity | 城市名,支持拼音和中文(建议) | 南京
remind-me.hefengAppkey | 和风天气KEY(免费),每日5000次调用 | “”
remind-me.lunchTime | 吃饭时间 | 11:30
remind-me.getOffTime | 下班时间 | 18:00

和风天气API提供每日5000次查询,估计 用不完。。

快捷键 ctrl+shift+, 看看有没有下雨

Enjoy!


development process

before:

  • vscode
  • node.js
  • npm
  • 天气数据API
  • generator-code
  • yo

npm i -g yo generator-code

process

起步:

yo code
  • 选择Javascript或者Typescript,填写项目名称、项目描述,publisher(我已经申请并配置好了,你初始化的时候没有),是否初始化git仓库

初始化步骤

  • 初始化完成后生成目录
├─ .vscode
├─ node_modules ## 依赖文件夹
├─ test ## 测试
│  .eslintrc.json
│  .gitattributes
│  .gitignore
│  .vscodeignore
│  CHANGELOG.md ## 更改日志
│  extension.js ## 入口
│  jsconfig.json ## js配置文件
│  package-lock.json
│  package.json ## 项目配置文件
│  README.md
└─ vsc-extension-quickstart.md
  • 我们的主要关注点在入口文件extension.js和项目配置文件package.json上,
// package.json
{
    "name": "remind-me",
    "displayName": "remind-me",
    "description": "remind you do sth",
    "version": "0.0.1",
    "publisher": "shehuiwang", 
    "engines": {
        "vscode": "^1.25.0"
    },
    "categories": [ // 分类
        "Other"
    ],
    "activationEvents": [ // 触发条件
        "onCommand:extension.sayHello"
    ],
    "main": "./extension",  // 入口文件
    "contributes": {
        "commands": [  // 对应命令
            {
                "command": "extension.sayHello",
                "title": "Hello World"
            }
        ]
    },
    "scripts": {
        "postinstall": "node ./node_modules/vscode/bin/install",
        "test": "node ./node_modules/vscode/bin/test"
    },
    "devDependencies": {
        "typescript": "^2.6.1",
        "vscode": "^1.1.6",
        "eslint": "^4.11.0",
        "@types/node": "^7.0.43",
        "@types/mocha": "^2.2.42"
    }
}
// extension.js
const vscode = require('vscode');
function activate(context) {
    // package.json 中的命令在这里定义
    let disposable = vscode.commands.registerCommand('extension.sayHello', function () {
       vscode.window.showInformationMessage('Hello World!');  // 弹出消息
    });
    context.subscriptions.push(disposable); // 订阅
}
exports.activate = activate; // 插件激活的时候执行本方法
function deactivate() {
}
exports.deactivate = deactivate; // 插件停用的时候执行本方法

debug

F5将弹出带有扩展开发主机标识的新窗口,ctrl+shift+p弹出的输入框中输入Hello world回车,即可看到通知消息。

  • 我们的目标功能

    • 获取城市天气;
    • 恶劣天气提醒;
    • 展示温度曲线;
    • 定时并弹出提醒;
    • 自动启动;

code

配置文件
// package.json
{
  "name": "remind-me",
  "displayName": "吃饭饭",
  "description": "Remind you to do something, lunch or get off work, etc.",
  "version": "1.0.1",
  "publisher": "shehuiwang",
  "license": "MIT",
  "icon": "icon.png",
  "engines": {
    "vscode": "^1.25.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/kelrvins/remind-me"
  },
  "categories": [
    "Other"
  ],
  "keywords": [
      "remind",
      "get off work",
      "lunch"
  ],
  "activationEvents": [
    "*"   // 据说这样配置就可以在vscode启动之后自动开启,但是我尝试了下触发概率有点低,没找到解决办法,<del>以后再试吧</del>
  ],
  "main": "./extension",
  "contributes": {
    "commands": [  // ctrl+shift+p 弹出框的命令
      {
        "command": "extension.remindMe",
        "title": "remind me"
      }
    ],
    "configuration": { // 设置中的配置项
      "type": "object",
      "title": "remind me configuration",
      "properties": {
        "remind-me.defaultCity": {
          "type": "string",
          "default": "南京",
          "description": "Set default city (eg.nanjing or 南京)"
        },
        "remind-me.hefengAppkey": {
          "type": "string",
          "default": "",
          "description": "You can get your private key from here: https://wx.jdcloud.com/market/datas/26/10610"
        },
        "remind-me.lunchTime": {
          "type": "string",
          "default": "11:30",
          "description": "set lunch times"
        },
        "remind-me.getOffTime": {
          "type": "string",
          "default": "18:00",
          "description": "set get off work time times"
        }
      }
    },
    "keybindings": [
      {
        "command": "extension.remindMe",
        "key": "ctrl+shift+,",
        "mac": "ctrl+shift+,"
      }
    ]
  },
  "scripts": {
    "postinstall": "node ./node_modules/vscode/bin/install",
    "test": "node ./node_modules/vscode/bin/test"
  },
  "dependencies": {
    "web-request": "^1.0.7"
  },
  "devDependencies": {
    "@types/mocha": "^2.2.42",
    "@types/node": "^7.0.43",
    "eslint": "^4.11.0",
    "typescript": "^2.6.1",
    "vscode": "^1.1.6"
  }
}
主体代码

注册指令extension.remindMe,并开启计时器,每60秒执行一次,到时间就提醒,不知道还有没有其他好方案本垃圾代码搬运工想不出来。

// extension.js

function activate(context) {
  let cityApi = vscode.commands.registerCommand('extension.remindMe', function() {
      const config = vscode.workspace.getConfiguration('remind-me')
      const reg = new RegExp(/^([01][0-9]|2[0-3]):([0-5][0-9])$/)
      const addZero1 = (num, len = 2) => `0${num}`.slice(-len)
      if ((config.lunchTime && reg.test(config.lunchTime))||(config.getOffTime && reg.test(config.getOffTime))) {   
        if (timer) clearInterval(timer)
        timer = setInterval(function() {
          const configTime = vscode.workspace.getConfiguration('remind-me')
          const [lh, lm] = configTime.lunchTime.split(':')
          const [gh, gm] = configTime.getOffTime.split(':')
          if ( lh && lm &&
            addZero1(new Date().getHours()) == lh &&
            addZero1(new Date().getMinutes()) == lm) {
            getWeatherInfo(configTime.defaultCity,1)
          }
          if (gh && gm &&
            addZero1(new Date().getHours()) == gh &&
            addZero1(new Date().getMinutes()) == gm) {
            getWeatherInfo(configTime.defaultCity,2)
          }
        }, 60000)  //一分钟执行一次,不是整点的,所以时间可能不准,是不是该考虑下提前一分钟提醒
      }
      if (config.defaultCity) { // 配置项里有默认值直接用
        getWeatherInfo(config.defaultCity)
      } else { // 配置项里没有默认值弹窗让用户填
        const options = {
          ignoreFocusOut: true,
          password: false,
          prompt: 'please input you city (eg.beijing or 北京),最好在配置文件里填一下'
        }
        vscode.window.showInputBox(options).then(value => {
          if (!value) {
            vscode.window.showInformationMessage('please input you city')
            return
          }
          const cityName = value.trim()
          getWeatherInfo(cityName)
        })
      }
    }
  )
  context.subscriptions.push(cityApi)
}
获取城市天气
WebRequest.get(`https://way.jd.com/he/freeweather?city=${encodeURI(cityName)}&appkey=${appkey}`).then(reps => {})

原本我是用axios做的网络请求,开发时预览没问题,但是打包之后作为visx安装就提示command extension.remindMe not found,为了解决这个问题刚了一个小时,后来通过查看开发者工具才发现根本原因是Cannot find module "axios",刚了半个小时没能找到解决办法,于是我找了其他的开源插件看代码,发现用的是WebRequest,一把辛酸泪。

绘制温度曲线

和风天气提供以3小时为间隔的温度数据,通过字符拼接的方式展示温度曲线,效果还可以:

温度曲线

/**
// extension.js

 * 绘制温度曲线
 * @param {Array} parm 天气数组
 */
function renderTmpLine(parm) {
  let array = []
  let weatherNotice = ''
  parm.forEach(el => {
    if (el.cond.code > 204 && !weatherNotice) {
      weatherNotice = ` , ${el.date.substr(8, 2) - new Date().getDate() > 0 ? '明天' : '今天'}${el.date.substr(-5, 2)}点后有${el.cond.txt}`
    }
    array.push(el.tmp)
  })
  const tmpSigns = ['__ ', '▁▁ ', '▂  ', '▃ ', '▅  ', '▆  ', '▇  ']
  const tmpRange = {
    max: Math.max.apply(Math, array),
    min: Math.min.apply(Math, array)
  }
  let tmpLine = ''
  array.forEach(el => {
    tmpLine += tmpSigns[el - tmpRange.min > 6 ? 6 : el - tmpRange.min]
  })
  return (tmpLine + weatherNotice + ', 最高: ' + tmpRange.max + '°C, 最低 : ' + tmpRange.min + '°C')
}
获取城市天气
/**
 * 获取城市天气
 * @param {string} cityName 城市名
 * @param {string} operation 中午饭、下班 标识
 */
function getWeatherInfo(cityName,operation=0) {
  const config = vscode.workspace.getConfiguration('remind-me') //获取可配置项中的数据
  const appkey = config.hefengAppkey
    ? config.hefengAppkey
    : 'YOUR_KEY' // 这里放和风天气的KEY
  WebRequest.get(`https://way.jd.com/he/freeweather?city=${encodeURI(cityName)}&appkey=${appkey}`).
  then(reps => {
    let rep = JSON.parse(reps.body)
    if (rep.code != 10000) {
      vscode.window.showInformationMessage('sorry please try again')
      return
    }
    const weatherData = rep.result.HeWeather5[0]
    if (weatherData.status !== 'ok') {
      vscode.window.showInformationMessage(`sorry,${weatherData.status}`)
      return
    }
    const tmpLine = renderTmpLine(weatherData.hourly_forecast)
    vscode.window.showInformationMessage(`未来十二小时温度曲线 :${tmpLine}`)
    const isRain =
      weatherData.hourly_forecast[0].cond.code >= 300 &&
      weatherData.hourly_forecast[0].cond.code < 500
    vscode.window.showInformationMessage(
      `${weatherData.basic.city}, ${weatherData.now.cond.txt}, ${weatherData.now.tmp}°C,未来两小时${weatherData.hourly_forecast[0].cond.txt}${isRain ? ' ,请携带雨具' : ''}`,
      ...[isRain ? ' 哦哦' : '']  
    ) // ...['哦哦'] 有雨的时候就加上这个,就是加个按钮弹窗就不会自动消失,我真贴心,以后混不下去了就做产品经理
    if(operation==1){
      vscode.window.showInformationMessage(`吃饭啦`)
    }
    if(operation==2){
      vscode.window.showInformationMessage(`下班啦`)
    }
  })
}

publish

准备工作

图片描述

  • 在右上角头像下的Security

图片描述

中新建一个access tokens,注意!!这个access tokens只显示一次,以后找不着了,注意记录,且创建access tokens的时候一定要选择所有权限,否则发布过程中会报错
图片描述

发布

设置好 icon,编辑好 readme 和 changeLog, 再删除一些多余的文件就可以上传到插件商店Extension Marketplace给其他人下载使用了;

输入vsce create-publisher [name]
这里的 [name] 就是刚刚新建账号的组织organizations名,填入邮箱和刚刚创建的 Access token

输入vsce publish 即可开始上传;

当你看到Successfully published ***的时候,上传成功!!


finish

附上 gayhub : https://github.com/kelrvins/remind-me

参考资料:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值